Reputation: 179
is it possible to turn two array into a specific format , because i need the specific format to create my D3 graph.
Actually, what i have , it's these two array,
date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"]
likes = [2,4,5]
and i want to turn into this format
[{ date: '...', likes: '...'},
{ date: '...', likes: '...'}]
Upvotes: 2
Views: 45
Reputation: 171679
Assuming they have the same length you can use Array.prototype.map():
var newArr = likes.map(function(item, index){
return { date: dates[index], like: item };
});
Upvotes: 1
Reputation: 167162
You can do it in a simple way:
date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"];
likes = [2,4,5];
final = [];
if (date.length == likes.length)
for (i = 0; i < dates.length; i++)
final.push({
date: dates[i],
likes: likes[i]
});
Also, checking both whether they are of same size, to make sure it should not go into an array index out of bound.
Upvotes: 2
Reputation: 32511
One way would be to use a simple for loop.
var result = [];
for (var i = 0, len = date.length; i < len; i++) {
result.push({
date: date[i],
likes: likes[i]
});
}
Note that this only works if the arrays are of the same length. If they aren't you could still get the maximum possible by taking the minimum of the two lengths.
var result = [];
var length = Math.min(date.length, likes.length);
for (var i = 0; i < length; i++) {
result.push({
date: date[i],
like: likes[i]
});
}
Upvotes: 1