Eusthace Eusthace - 1 year ago 193
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.


For example:

My object is:

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

My array arr:


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

Thank you.

Answer Source

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))) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download