0

I've got an array:

var objArray = [
   { id: 0, name: ‘Object 0’, otherProp: ‘321’ },
   { id: 1, name: ‘O1’, otherProp: ‘648’ },
   { id: 2, name: ‘Another Object’, otherProp: ‘850’ },
   { id: 3, name: ‘Almost There’, otherProp: ‘046’ },
   { id: 4, name: ‘Last Obj’, otherProp: ‘984’ },
   { id: 0, name: ‘Object 0’, otherProp: ‘321’ }
];

here the id 0 add twice. I only want an array that not have the same objects.

expected output:

a = [
   { id: 0, name: ‘Object 0’, otherProp: ‘321’ },
   { id: 1, name: ‘O1’, otherProp: ‘648’ },
   { id: 2, name: ‘Another Object’, otherProp: ‘850’ },
   { id: 3, name: ‘Almost There’, otherProp: ‘046’ },
   { id: 4, name: ‘Last Obj’, otherProp: ‘984’ }] 

How do I do this in JavaScript.

Hasibul-
  • 1,192
  • 1
  • 9
  • 18

1 Answers1

3

You could filter the array by looking for the id in a Set.

var array = [{ id: 0, name: 'Object 0', otherProp: '321' }, { id: 1, name: 'O1', otherProp: '648' }, { id: 2, name: 'Another Object', otherProp: '850' }, { id: 3, name: 'Almost There', otherProp: '046' }, { id: 4, name: 'Last Obj', otherProp: '984' }, { id: 0, name: 'Object 0', otherProp: '321' }],
    seen = new Set,
    result = array.filter(({ id }) => !seen.has(id) && seen.add(id));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392