How do I reformat a javascript cdata string into array? - javascript

Still learning... sorry if this doesn't make sense or sounds stupid :P
I have 2 variables "timestamps" and "clicks" and a string of numbers:
{
"timestamps":[
1362096000000,1362355200000,1362441600000,1362528000000
],
"clicks":[
[
1,2,3,4
]
};
What would be the easiest way to reformat the string and output into an array like this:
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4],

Just based on the limited information you've given us, and assuming the constraints of both timestamps and clicks always being the same length of arrays, and that you want the output to be an array this will create the new desired format.
var output = [];
for (var i = 0, l = obj.timestamps.length; i < l; i++) {
output.push([obj.timestamps[i], obj.clicks[i]]);
}
/*output is now [
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4]
]*/

Related

Add values into 2D dimensional array in JS

I'm trying to add values into 2D array based on the position that is present in the input data.
For example, the below format represents 0 as row, 0 as column and 5 is length of the value.
[
"0,0,5",
"hello"
],
How do I insert the values into 2D array based on position like [0][0], [0][1] and [0][2]?
Except from my code
const data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
let array2D = [
[]
];
let i = 0
for (let r = 0; r < data.length; ++r) {
array2D[r] = [];
for (let c = 0; c < data.length; ++c) {
array2D[r][c] = data[i++];
}
}
console.log(array2D);
Ok, thank you for your input.. it means that I'll just make a function to place into an array with 4 arguments.. col,row,arr&data
//important function
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
var array2dArray=[]
//this loop would take the data array and place the entire index in the desired destination
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,array2dArray,a) //the data to put into each part of the 2d array would an array itself(like data[0])
})
console.log(array2dArray)
//but I might just wanna put the text in the 2d array
var text2dArray=[]
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,text2dArray,a[1]) //the data to be put in each part of the 2d array would be the a text variable(like data[0][1] is "hello")
})
console.log(text2dArray)
<script>
//sry it just takes space in the js part that's unnessecary
window.data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
</script>
With this function, you can take an empty array, place row 10 col 4 in empty array putting any data like 'xD' and it will work out eg: try place2d(10,4,emptyArrName,"xD") and it works.. just one thing to note..
IT ONLY APPLIES array structures to WHERE IT NEEDS TO.. doing things like the example above would leave a lot of undefined slots.. wild example below
//now for a wild example to show that the function works
window.data2=[
["text for [10][0]","0/10"],
["text for [2][5]","5/2"]
]
//don't forget the placer function :D
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
//at the end of the day, all I'm changing is the information I make out of the array in the forEach loops in order to simply place in the function
var finalArray=[]
place2d(3,4,finalArray,"randomDataThatCouldBe_ANYTHING_notJustText")
data2.forEach(a=>{
var [col,row]=a[1].split('/')
place2d(row,col,finalArray,a[0])
})
console.log(finalArray)

javascript json get data names out for object

Still newbie #this, hope not a silly question.
I get from a java backend a json.
For this question I assigned a with that json string.
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
let b=a.data;
let s="";
for (i in b) {s += b[i]};
$('#msg').html(s);
As output I get object Object (small capital, big capital)
In the end I need to run over "data' and print or store that keynames : blablaMOUTI blablaDAN , blablaDAA blablaALHAZO ... on screen or in a simple array list.
The values after the keynames or a empty string, that's fine, I need only the keynames.
Found some semi simular questions, but I don't get it to work. The answers I found all trust I know already the keynames.
You can do it like this:
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
var keys = [];
for(i = 0; i< a.data.length; i++){
for(var k in a.data[i]) {
keys.push(k);
}
}
console.log(keys)
For testing purpose this will populate an array with keys that you wanted, but you can manipulate the result as you wish
Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
Try this:
Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

Angularjs splitting into array

I want my data to be stored in an array but mine is stored in a single array, how to split it into like array. This is how it looks like, im spliting it via "|" but i want to store them into array~
JS:
{
$scope.polygonPoints.push($scope.apiResult[i].LatLng)
$scope.polyLineCord.push($scope.polygonPoints[i].split("|"))
console.log($scope.polygonPoints)
for (var k= 0; k < $scope.polyLineCord.length; k++) {
console.log($scope.polyLineCord)
$scope.Lat.push($scope.polyLineCord[k].split(',')[0]);
$scope.Lng.push($scope.polyLineCord[k].split(',')[1]);
L.marker([$scope.Lat[k], $scope.Lng[k]], {icon: greenIcon}).bindPopup($scope.apiResult[k].DESCRIPTION).addTo(cities);
}
}
Sry if the phrasing sounds werid, basically what I want it like "1.309..., 103.844" into array[0] and and "1.30916..., 103.845..." into array1 and so on
You can use es6 features using map for example :
$scope.polygonPoints = ["1.3|1.2|1.5", "1.5|2.2"];
$scope.polygonPoints.map(res => res.split('|'));
result:
["1.3", "1.2", "1.5"] // array one
["1.5", "2.2"] // array two

how to find identical strings in a array of place names from a survey (using javascript)

This is my first time on here, so forgive me if the answer to this is obvious - but can't find a possible solution anywhere.
I'm trying to pull numbers out of a survey I want to set up, which will generate a list of cities. Thus:
var cities = array ['city1', 'city2', 'city3', 'city2', 'city4', 'city1', city2'];
Will generate a list: city1: 2, city2: 3, city3: 1, city4: 1
Is there a way to go through an array like this in Javascript? The cities will not be pre-determined - ie people could be entering anything.
Thanks in advance for any help you can give me.
tim
Like Niet already answered:
You go through the list and put the keys into a object and increment the values.
var generatedList = {};
for(var i=0;i<cities.length;i++){
if(generatedList[cities[i]]){
generatedList[cities[i]]++;
}else{
generatedList[cities[i]] = 1;
}
}
The answer is "obvious"... if you know where to start. So here's the starting line:
Create an object (literal, {})
Iterate through the array. For each item:
If the item doesn't exist as a key of the object, create the key with value 0
Increment the key on the object by 1
And... done! That's all there is to it.
This has been answered since I started this demo but this should help you understand what's happening. Open this demo with the developer console open to view the output:
http://jsfiddle.net/46wnj/
var cities = new Array('city1', 'city2', 'city3', 'city2', 'city4', 'city1', 'city2');
var citiesObject = {};
for (var x = 0; x < cities.length; x++)
{
if (citiesObject[cities[x]])
{
citiesObject[cities[x]]++
}
else
{
citiesObject[cities[x]] = 1;
}
}

Hash Tables in javascript

I am trying to build a data structure.
In my limited knowledge, 'hash table' seems to be the way to go. If you think there is an easier way, please suggest it.
I have two, 1-dimensional arrays:-
A[] - contains names of badges (accomplishment)
B[] - contains respective dates those achievements were accomplished from array A[].
An achievement/accomplishment/badge can be accomplished more than one time.
Therefore a sample of the two arrays:-
A['scholar', 'contributor', 'teacher', 'student', 'tumbleweed', 'scholar'.....,'scholar',......]
B['1/2010', '2/2011', '3/2011', '6/2012', '10/2012', '2/2013',......'3/2013',........]
What I want to achieve with my data structure is:-
A list of unique keys (eq:- 'scholar') and all of its existing values (dates in array B[]).
Therefore my final result should be like:-
({'scholar': '1/2010', '2/2013', '3/2013'}), ({'contributor' : ........})..........
This way I can pick out a unique key and then traverse through all its unique values and then use them to plot on x-y grid. (y axis labels being unique badge names, and x axis being dates, sort of a timeline.)
Can anyone guide me how to build such a data structure??
and how do I access the keys from the data structure created.... granted that I don't know how many keys there are and what are their individual values. Assigning of these keys are dynamic, so the number and their names vary.
Your final object structure would look like this:
{
'scholar': [],
'contributor': []
}
To build this, iterate through the names array and build the final result as you go: if the final result contains the key, push the corresponding date on to its value otherwise set a new key to an array containing its corresponding date.
something like:
var resultVal = {};
for(var i = 0; i < names.length; ++i) {
if(resultVal[names[i]]) {
resultVal[names[i]].push(dates[i]);
} else {
resultVal[names[i]] = [dates[i]];
}
}
Accessing the result - iterating through all values:
for(var key in resultVal) {
var dates = resultVal[key];
for(var i = 0; i < dates.length; ++i) {
// you logic here for each date
console.log("resultVal[" + key + "] ==> " + resultVal[key][i]);
}
}
will give results like:
resultVal[scholar] ==> 1/2010
resultVal[scholar] ==> 2/2013
resultVal[scholar] ==> 3/2013
resultVal[contributor] ==> 2/2011
resultVal[teacher] ==> 3/2011
resultVal[student] ==> 6/2012
resultVal[tumbleweed] ==> 10/2012
You can try this...
var A = ['scholar', 'contributor',
'teacher', 'student', 'tumbleweed', 'scholar','scholar'];
var B = ['1/2010', '2/2011',
'3/2011', '6/2012', '10/2012', '2/2013','3/2013'];
var combined = {};
for(var i=0;i<A.length;i++) {
if(combined[A[i]] === undefined) {
combined[A[i]] = [];
}
combined[A[i]].push(B[i]);
}
Then each one of the arrays in combined can be accessed via
combined.scholar[0]
or
combined['scholar'][0]
Note the === when comparing against undefined

Categories