0

Hi I'm trying to remove duplicates from array of objects. But that is not working as expected.

This is my array:

const arr = [{
  PData: [{
      id: '1',
      name: 'Book'
    },
    {
      id: '2',
      name: 'Bag'
    },
    {
      id: '2',
      name: 'Bag'
    },
  ]
}]

const RemoveDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};
var result = RemoveDuplicates(arr, 'id')
console.log(result);

Expected output:

[{
  PData: [{
      id: '1',
      name: 'Book'
    },
    {
      id: '2',
      name: 'Bag'
    },
  ]
}]

Based on id it supposed to remove duplicates but this is not happening currently..I know that couple of questions are existed regarding this but nothing is working for me. So anyone plz suggest me how to do.

SAMUEL
  • 8,098
  • 3
  • 42
  • 42
Jayden
  • 273
  • 2
  • 6
  • 16
  • The array you want to remove duplicates from is nested in an object but you're only running your function on the 'root' array – Lennholm Mar 16 '20 at 11:49

1 Answers1

0

You can use filter here is how on id and name.

const arr = [{
  PData: [{
      id: '1',
      name: 'Book'
    },
    {
      id: '2',
      name: 'Bag'
    },
    {
      id: '2',
      name: 'Bag'
    },
  ]
}]
arr[0].PData = Object.values(arr[0].PData).filter((v,i,a)=>a.findIndex(t=>(t.id === v.id && t.name=== v.name))===i)
console.log(arr[0].PData);
manikant gautam
  • 3,521
  • 1
  • 17
  • 27