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.

1
  • The array you want to remove duplicates from is nested in an object but you're only running your function on the 'root' array Commented Mar 16, 2020 at 11:49

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

But my array is not like that right
@royal see the update

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.