Home > Mobile >  Find the unique id of the item and group its value in array using reduce method?
Find the unique id of the item and group its value in array using reduce method?

Time:09-19

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

CodePudding user response:

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

CodePudding user response:

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

Thanks & Regards

  • Related