简体   繁体   中英

Group and sum of an array of objects based on number key

I am trying to create a statistical pie chart. As a http response i am getting a list from server using which i need to draw a pie chart.

For example: Data received:

[{1: 9, 2: 7}, {3:8, 2: 1}, {1:8, 5:9}, {2:3, 3:1}]

This is the desired output:

[{x: 1, y: 17}, {x: 2, y:10}, {x: 3, y: 9}, {x: 5, y: 9}]

Please note: x is the key and y is sum of similar key values

I have tried data.forEach((item, index) => {}) . After writing this, I am actually getting no lead about how I can combine Object.keys(item) , Object.values(item) and Object.values(item).reduce((a,b)=> return a+b;)

This may sound silly question, but any help would be appreciated. :)

You could reduce the array. Create an accumulator object with each number as key and and object with x and y keys as it's value. Loop through each object and update the y value based on the number. Then use Object.values() on the object returned to get the values of the accumulator as an array

 const input = [{1: 9, 2: 7}, {3:8, 2: 1}, {1:8, 5:9}, {2:3, 3:1}] const grouped = input.reduce((acc, obj) => { for (const x in obj) { acc[x] = acc[x] || { x , y: 0 } acc[x].y += obj[x] } return acc; }, {}) console.log(Object.values(grouped)) 

You could look for same key and update or insert a new object.

This approach does not change the order of the keys.

 var data = [{ 1: 9, 2: 7 }, { 3: 8, 2: 1 }, { 1: 8, 5: 9 }, { 2: 3, 3: 1 }] , result = data.reduce((r, o) => { Object.entries(o).forEach(([x, y]) => { var temp = r.find(o => ox === x); if (temp) temp.y += y; else r.push({ x, y }); }); return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM