-3

I am trying to merge an array of objects with the given input with an array of objects to get the below output.Looking for a possible solution to implement this with array.reduce. Input:

const items = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 1, name: 'd' },
{ id: 3, name: 'f' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' },
]

output:

[
{ id: 1, names: ['a', 'd']},
{ id: 2, names: ['b']},
{ id: 3, names: ['c', 'f']}
]
Ankita Sinha
  • 53
  • 1
  • 8

1 Answers1

-1
    function test(ar) {
  let obj = {};
  ar.map((val, i) => {
    let ar=[]
    if (obj[val.id]) {
     obj[val.id].push(val.name)
    }else{
      obj[val.id] = [...val.name];
    }
  });
  //console.log(obj)
  let result=[]
  for(let key in obj){
    result.push({
      id:key,names:[...new Set(obj[key])]
    })
  }
  return result
}


console.log(test([
  { id: 1, name: "a" },
  { id: 2, name: "b" },
  { id: 3, name: "c" },
  { id: 1, name: "d" },
  { id: 3, name: "f" },
  { id: 1, name: "a" },
  { id: 3, name: "c" },
]));
Ankita Sinha
  • 53
  • 1
  • 8