Eusthace Eusthace - 1 month ago 8
TypeScript Question

Typescript Array insert non-duplicate item

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.

Answer

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