0

My question is how can I pass from this :

const array = [
    {name: "Bline", score: 95},
    {name: "Flynn", score: 75},
    {name: "Carl", score: 80},
    {name: "Bline", score: 77},
    {name: "Flynn", score: 88},
    {name: "Carl", score: 80}
]

to this array of objects using javascript:

[
    {
      name: 'Bline',
      data: [95, 77]
    }
    {
      name: 'Flynn',
      data: [75, 88]
    }
    {
      name: 'Carl',
      data: [80, 80]
    }
    ]

I have tried using the duplicate but nothing so far

2 Answers 2

2

you should iterate over your array and set name as key and score as value in an array manner in an object:

let result = {}
for (let item of array) {
  if (!result[item.name]) result[item.name] = [item.score]
  else result[item.name].push(item.score)
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can get the expected result by first grouping the data with a reduce function.

let grouped = array.reduce(function (r, a) {
    r[a.name] = r[a.name] || [];
    r[a.name].push(a.score);
    return r;
}, {});

And then format it to what you wanted.

let formated = Object.entries(grouped).map(([key, value]) => {
    return {
        name : key,
        data: value
    }    
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.