D
D
Dmitry Gololobov2019-04-07 19:13:11
JavaScript
Dmitry Gololobov, 2019-04-07 19:13:11

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 } 
]

From it you need to get an array without duplicate id, but the duration parameter must be summed, i.e.:
[ 
{ 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

1 answer(s)
0
0xD34F, 2019-04-07
@dGololobov

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] }))

or
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 question

Ask a Question

731 491 924 answers to any question