I have been trying to figure this out for a long time, if i have an array of objects like so:
var my_array = [
Object {Project: A, Hours: 2},
Object {Project: B, Hours: 3},
Object {Project: C, Hours: 5},
Object {Project: A, Hours: 6},
Object {Project: C, Hours: 9}
]
I want to merge all the objects with the same key together into one object, such that their hours get added up:
Expected output:
my_array = [
Object {Project: A, Hours: 8}
Object {Project: B, Hours: 3}
Object {Project: C, Hours: 14}
]
How can I approach this issue? It has taken me a long time to get my data formatted in this way, this is the last step!
My attempt, I get that I am looping through array, not sure how to deal with the merging of the objects:
for (var i =0; i<my_array.length; i++) {
my_array[i].Project // access the object project key
my_array[i].Hours // need to increment hours
}
You create another object where you can actually group the projects and accumulate the corresponding hours, like this
At this point, your
groups
will look like thisNow, you just have to expand this object, like this
Now, the result will be
In your attempt, you are missing out on creating a new array
Now create the final output array out of uniqueproject map
Both
thefourtheye
's andgurvinder372
's proposed solutions work, so I set up a benchmark test on jsPerf to test which is faster. You can see it here.It appears that
gurvinder372
's code is by far the fastest.P.S. please ignore the
Uncaught TypeError
as it is a jsPerf issue currently being fixed that has nothing to do with the results of the test. For more info, see this and this.