2

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: '...'}]

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]
  });
}

Comments

1

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 };
});

2 Comments

Won't this affect the likes array? Just curious to know. :)
@PraveenKumar no, returns new array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.