Push Element to Array if it does not exist in JavaScript

Updated onbyAlan Morel
Push Element to Array if it does not exist in JavaScript

When you want an array to only consist of unique elements, you'll need to control when you push to it.

More specifically, you'll need to first check if an element exists in the array before pushing it.

In this post, we'll learn how you can create and maintain an array of unique values and only push an element to it if it doesn't already exist.

Checking if an element exists in an array

To determine if an element can be pushed to our array, we'll need to first check if it exists in the array.

The best way to check if an element exists in an array of primitives is to use the includes() method.

This method takes an element and returns a boolean value.

JAVASCRIPT
const array = [1, 2, 3, 4, 5]; const value = 6; const exists = array.includes(value); console.log(exists);
BASH
false

If your array uses objects, you can use findIndex and define a custom function to determine if the element was found.

The findIndex method will return to you the index of the element where your custom function returns true.

When the element is not found, the method will return an index of -1.

Since it just returns a number, you will need to compare it to -1 to get a boolean.

JAVASCRIPT
const array = [{ id: 1 }, { id: 2 }, { id: 3 }]; const value = { id: 4 }; const exists = array.findIndex(element => element.id === value.id) > -1; console.log(exists);
BASH
false

Pushing an element to an array

Now that you've determined how to check if an element exists in an array, you can use the push() method to push an element to the array.

Here's the example using primitives:

JAVASCRIPT
const array = [1, 2, 3, 4, 5]; const value = 6; const exists = array.includes(value); if (!exists) { array.push(value); } console.log(array);
BASH
(6) [1, 2, 3, 4, 5, 6]

Here's the example using objects:

JAVASCRIPT
const array = [{ id: 1 }, { id: 2 }, { id: 3 }]; const value = { id: 4 }; const exists = array.findIndex(element => element.id === value.id) > -1; if (!exists) { array.push(value); } console.log(array);
BASH
(4) [{…}, {…}, {…}, {…}] 0: {id: 1} 1: {id: 2} 2: {id: 3} 3: {id: 4} length: 4

Conclusion

In this post, we learned how to maintain a unique array of values and only push an element to it if it doesn't already exist.

Make sure to remember that for primitive values, you should use includes() to check if an element exists in an array, but for objects, you should use findIndex().

Hopefully, this was helpful to you. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.