I’m stuck at transforming a data structure:
JavaScript
x
14
14
1
let d = [
2
{ no: 1, score: 7000 },
3
{ no: 2, score: 10000 },
4
[
5
{ no: 1, score: 8500 },
6
{ no: 2, score: 6500 }
7
]
8
];
9
10
11
d = d.reduce((accum, o) => {
12
13
}, [])
14
How can I produce this?
JavaScript
1
2
1
[{name: 'no 1', score: [7000, 8500]}, {name: 'no 2', score: [10000, 6500]}]
2
Advertisement
Answer
Here is one way to do it with simple reduce
,
JavaScript
1
15
15
1
const result = d.flat().reduce((acc: {name: string, score: number[]}[], curr) => {
2
const { no, score } = curr;
3
let item = acc.find(a => a.name === `no ${no}`);
4
if (!item) {
5
item = { name: `no ${no}`, score: []};
6
acc.push(item);
7
}
8
9
item.score.push(score);
10
return acc;
11
12
}, []);
13
14
console.log(result)
15