1

I have:

arrayBefore

arrayBefore = [{name:'n1', items: [i1]}, {name:'n2', items: [i2]}, {name:'n1', items: [i3]}]

I want to create a function:

myFunction

myFunction(arrayBefore)

So it will produce:

arrayAfter

arrayAfter = [{name:'n1', items: [i1, i3]}, {name:'n2', items: [i2]}]

I have tried to implement myFunction using map() and filter(), but I can't get it working correctly. I would show some code I tried if I had the idea I was getting close, unfortunatly this is not the case. Any help would be greatly appreciated!

Niels Ferguson
  • 352
  • 1
  • 6
  • 16

2 Answers2

1

This looks like the groupBy operation. It's not doable by only map and filter. You need a reduce. See an example here

Tiberiu Maran
  • 1,983
  • 16
  • 23
  • It seems like the example was indeed the solution. I accepted the answer from @StepUp because it was the first correct one to come in. – Niels Ferguson Dec 20 '19 at 09:16
1

reduce method is what you are looking for:

const result = arr.reduce((a, {name, items})=>{
     a[name] = a[name] || { name, items:[] };
     a[name].items.push(...items)
     return a;
 }, {});

An example:

let arr = [
    { name: 'n1', items: ['i1'] },
    { name: 'n2', items: ['i2'] },
    { name: 'n1', items: ['i3'] }
];

const result = arr.reduce((a, {name, items})=>{
     a[name] = a[name] || { name, items:[] };
     a[name].items.push(...items)
     return a;
 }, {});
 
 console.log(Object.values(result))
StepUp
  • 36,391
  • 15
  • 88
  • 148