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.

10
  • Please also add the expected output. Commented Jul 8, 2019 at 11:07
  • 1
    What should happen if a duplicate ID is used? Don't insert the entry? Remove the previous entry? Commented Jul 8, 2019 at 11:08
  • 1
    You are considering duplicates using id only ? Commented Jul 8, 2019 at 11:12
  • 1
    George Bailey this only work for string not for objects Commented Jul 8, 2019 at 11:13
  • 1
    @Alexander yet it's trivial to adapt the code for arbitrary objects by comparing the property you want to consider unique (id in this case) instead of the item itself. We don't need a different question for each different case when it is all the same logic in the end. Commented Jul 8, 2019 at 11:32

1 Answer 1

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

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

1 Comment

Thanks Nina Scholz :) it's working

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.