1

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. :)

1
  • @Andreas, 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;) else i would have posted. Commented Jul 8, 2019 at 8:00

2 Answers 2

2

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

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

Comments

0

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 => o.x === 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; }

Comments

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.