Answer the question
In order to leave comments, you need to log in
How to join array elements in js?
There is an array with a duplicate id:
[
{ id: '235540633', duration: 163 },
{ id: '222333444', duration: 100 },
{ id: '112233445', duration: 31 },
{ id: '112233445', duration: 63 }
]
[
{ id: '235540633', duration: 163 },
{ id: '222333444', duration: 100 },
{ id: '112233445', duration: 94 }
]
Answer the question
In order to leave comments, you need to log in
Object.entries(arr.reduce((acc, n) => {
acc[n.id] = (acc[n.id] || 0) + n.duration;
return acc;
}, {})).map(n => ({ id: n[0], duration: n[1] }))
const grouped = arr.reduce((acc, n) => {
let obj = acc.find(m => m.id === n.id);
if (!obj) {
acc.push(obj = { id: n.id, duration: 0 });
}
obj.duration += n.duration;
return acc;
}, [])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question