-1

I've got an array of objects. All I want is to check if the ids of the objects are the same and return that particular object, without duplication.

example.

let arr1 = [
{id: 1, name: 'A'},
{id: 3, name: 'C'},
{id: 1, name: 'A'},
{id: 2, name: 'B'},
{id: 2, name: 'B'}
]

result I want:

let newArr = [
{id: 1, name: 'A'},
{id: 2, name: 'B'}
]

result I get:

let arr1 = [
{id: 1, name: 'A'},
{id: 3, name: 'C'},
{id: 2, name: 'B'}
]

I tried:

arr1.reduce((destArray, obj) => {
    if (destArray.findIndex(i => i.id === obj.id) < 0) {
      return destArray.concat(obj);
    } else {
      return destArray;
    }
  }, [])

As a result, I get objects with matching ids, BUT there're also objects with kinda unique id. But I don't need them.

nini
  • 1
  • 2
  • 2
    You said that you don't want duplicates, and the result you got does not contain any. What's the problem then? – Ar Rakin Mar 29 '23 at 19:28
  • 2
    Sounds like you want to retrieve all the duplicates, from `result I want` example. – James Mar 29 '23 at 19:31
  • possibly see: [Get list of duplicate objects in an array of objects](https://stackoverflow.com/questions/53212020/get-list-of-duplicate-objects-in-an-array-of-objects) – pilchard Mar 29 '23 at 19:39

1 Answers1

0
const newArr = arr1.filter((obj, index, self) => {
return self.findIndex(i => i.id === obj.id) === index && self.lastIndexOf(i => i.id === obj.id) !== index;
});
DomeQ
  • 9
  • 4