Languages
[Edit]
EN

JavaScript - array push() if element doesn't exist in array

0 points
Created by:
Frida-Timms
667

In this article, we would like to show you how to push an element into an array if doesn't exist using JavaScript.

Quick solution for primitive values:

 

1. Compare objects by property

Edit

In this example, we compare objects by a single property - id using findIndex() method. If the object with such id doesn't already exist it will be added using push() method.

Note:

The findIndex() method returns -1 if no element passes the provided test.

2. Compare multiple object properties

Edit

In this example, we create pushIfNotExist() function that uses compare() function to push an object into an myArray if it doesn't already exist. The compare() checks if an object exists in the array by executing the comparator function on every element in array.

 

References

Edit
  1. Array.prototype.push() - JavaScript | MDN
  2. Array.prototype.includes() - JavaScript | MDN
  3. Array.prototype.findIndex() - JavaScript | MDN

Alternative titles

  1. JavaScript - array push() if element does not exist in array
  2. JavaScript - push element into array if doesn't exist
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join