Here's a sleek functional solution for typescript, since you included the tag-
const arr = [
{ no: 1, score: 7000 },
{ no: 2, score: 10000 },
[
{ no: 1, score: 8500 },
{ no: 2, score: 6500 },
],
];
const result = Object.entries(
arr.flat().reduce((accum: { [key: number]: number[] }, el: { no: number; score: number }) => {
accum[el.no] = (accum[el.no] ?? []).concat(el.score);
return accum;
}, {})
).map(([num, scores]) => ({ no: Number(num), scores: scores }));
console.log(result);
Result-
[
{ no: 1, scores: [ 7000, 8500 ] },
{ no: 2, scores: [ 10000, 6500 ] }
]
This flattens the inner arrays first using Array.prototype.flat
. Then it uses reduce
to construct an object that has the no
values as keys and score
values as an array of values.
In the end, the reduce results in { 1: [7000, 8500], 2: [10000, 6500] }
- turn that into entries using Object.entries
to get [['1', [7000, 8500]], ['2', [10000, 6500]]]
Finally, map over the entries to turn the ['1', [7000, 8500]]
format into { no: 1, scores: [ 7000, 8500 ] }
format and you're done!