-7

Please help me to find the expected output from the given scenario

input array:

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

expected output:

[{ id: 1, names: ['a', 'd']},
    { id: 2, names: ['b']},
    { id: 3, names: ['c', 'f']}]
Srisan Gj
  • 1
  • 2
  • You can find the solution in the following link https://stackoverflow.com/questions/62139362/remove-duplicate-keys-and-combine-unique-values-in-javascript-array Thanks – Anjali Paliwal Sep 19 '22 at 08:56
  • You can follow the logic from these answers and then remove the duplicate items: [Group array items using object](https://stackoverflow.com/q/31688459) – Nick Parsons Sep 19 '22 at 08:59

2 Answers2

0

You can create a new array, loop through your main array and check if there is an object with the current id in the new array and update it or create a new object accordingly.

Like this:

let newItems = [];

items.forEach(item => {
  let index = newItems.findIndex(el => el.id == item.id);
  
  if (index > -1) {
    if (newItems[index]['names'].indexOf(item.name) === -1) {
      return newItems[index]['names'].push(item.name)
    }
  } else {
    newItems.push({id: item.id, names: [item.name]});
  }
});

With reduce method:

const newArr = items.reduce((pv, cv) => {
  let index = pv.findIndex(el => el.id == cv.id);
  if (index > -1) {
    if (pv[index]['names'].indexOf(cv.name) === -1) {
      pv[index]['names'].push(cv.name)
    }
  } else {
    pv.push({id: cv.id, names: [cv.name]});
  }
  return pv;
}, []);

pv is previous value which is the new array, cv is current value which is each object in items array. Initial value of newArr is []

Feyyaz
  • 561
  • 1
  • 5
  • 12
-1

You can use spread operator and retrieve the values of the duplicate key and push it in the new array of objects.

Thanks & Regards

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 22 '22 at 23:21