I have an array of objects something like the following: -
0: {Id: 0, count1: 5, count2: 10, yearMonth: "201803"}
1: {Id: 0, count1: 10, count2: 0, yearMonth: "201804"}
2: {Id: 1, count1: 900, count2: 200, yearMonth: "201805"}
3: {Id: 0, count1: 10, count2: 0, yearMonth: "201806"}
4: {Id: 1, count1: 100, count2: 100, yearMonth: "201807"}
5: {Id: 1, count1: 100, count2: 2, yearMonth: "201808"}
I want to sum similar keys to get Expected output:
1: {Id: 0, count1: 25, count2: 10}
2: {Id: 1, count1: 1100, count2: 402}
Is it possible to achieve it using any mathematical operation or reduce or any other javascript method?
Thanks
You could reduce the array by using a hash table and an array of keys for summing the wanted values.
With knockout, you can use a chain of computed properties to get to the desired (UI?) format!
Disclaimer: I'm assuming this list will not contain thousands of items
1. Grouping
The first step is to go from a list (
ko.observableArray([])
) of items to a computed object that groups by id:2. Merging
Now that we have grouped lists of items that need to be summarized, we can start applying our merge logic:
3. Going back from indexed object to array
Now that we know how to merge our groups, we can move back to the array we need in our UI: