1

We are in 2016, so, I would like to know the best way to insert a non-duplicate item into an array taking into account performance and clean code.

EDIT:

For example:

My object is:

obj = {id: 1, a: 2, b: 3, c: 4}

My array arr:

arr.push(obj);

arr.push(obj); // Avoid this duplicate obj

Thank you.

2
  • You need to more specific, e.g. what identifies a duplicate item. Commented Oct 24, 2016 at 9:32
  • I've updated my question, ok? Thank you! Commented Oct 24, 2016 at 10:00

1 Answer 1

2

There is no native pushIfUnique in the language, so you have to options:

(1) If ordering is not important just use a Map an the id (or whatever) as identifier.

(2) If ordering is important you can write a small helper function by using Array.find. E.g.:

const pushIfUnique = (predicate, object, array) => {
  if (!array.find(item => predicate(object, item))) {
    array.push(object);
  }
};
Sign up to request clarification or add additional context in comments.

2 Comments

Well, if you only use a property subset to identify an object (= unique because of id for example) I guess Set will not have any benefits for you, b/c has only works with the whole stored value. So you would have to iterate over the entries anyway.
Ahh, you're amazing! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.