Skip to content
Advertisement

reduce array of array into a flat array of object

I’m stuck at transforming a data structure:

let d = [
  { no: 1, score: 7000 },
  { no: 2, score: 10000 },
  [
    { no: 1, score: 8500 },
    { no: 2, score: 6500 }
  ]
];

    
d = d.reduce((accum, o) => {
   
}, [])

How can I produce this?

[{name: 'no 1', score: [7000, 8500]}, {name: 'no 2', score: [10000, 6500]}]

Advertisement

Answer

Here is one way to do it with simple reduce,

const result = d.flat().reduce((acc: {name: string, score: number[]}[], curr) => {
  const { no, score } = curr;
  let item = acc.find(a => a.name === `no ${no}`);
  if (!item) {
    item = { name: `no ${no}`, score: []};
    acc.push(item);
  }

  item.score.push(score);
  return acc;
    
}, []);

console.log(result)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement