I’m trying to take an array of many arrays that contain many objects and manipulate it into an array of objects.
So, let’s say I have an array that looks like this:
[
[
{Name: 'Josh', email: 'josh@gmail.com', Points: 33},
{Name: 'Doug', email: 'doug@gmail.com', Points: 12}
],
[
{Name: 'Josh', email: 'josh@gmail.com', Points: 11},
{Name: 'Doug', email: 'doug@gmail.com', Points: 18}
],
[
{Name: 'Josh', email: 'josh@gmail.com', Points: 2},
{Name: 'Doug', email: 'doug@gmail.com', Points: 27}
]
]
The Desired outcome would be an array of objects that has a ‘Points’ property to hold an array of the points. So it would look like this:
[
{Name: 'Josh', email: 'josh@gmail.com', Points: [33, 11, 2]},
{Name: 'Doug', email: 'doug@gmail.com', Points: [12, 18, 27]}
]
This problem seems simple, but I can’t seem to figure out the best way of doing this. If you want this data in a fiddle, I made this for you to play with: http://jsfiddle.net/Qhxzz/1/
Here’s one way using
.reduce()and.forEach(). (You’ll need patches if you’re supporting older browsers.)And actually, we could flatten out the original Array using
concat.apply(), and be left with one monolithic Array to iterate.This turns your
datainto this structure:And makes the consolidation a bit simpler by eliminating the need for the inner
.forEach().