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.
const array = [1, 2, 3, 4, 5];
const value = 6;
const exists = array.includes(value);
console.log(exists);
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.
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);
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:
const array = [1, 2, 3, 4, 5];
const value = 6;
const exists = array.includes(value);
if (!exists) {
array.push(value);
}
console.log(array);
(6) [1, 2, 3, 4, 5, 6]
Here's the example using objects:
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);
(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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!