In JavaScript, arrays allow duplicating elements and don’t guarantee the uniqueness of their elements.
However, in many cases, we need to push an element into an array only if it didn’t exist beforehand and ignore the process if it already exists.
So, how can we achieve this goal? I think that once you land on this page, you need a quick solution without much stuffing.
So, without further ado, let’s introduce the easiest and the more practical methods.
JavaScript Set
is a collection of unique values. Each value has to occur once in a Set.
If your array’s elements were strings or numbers, Set
is the easiest way to achieve your goal.
These two ways would work fine if your array’s elements were strings or numbers as well.
Firstly, let’s try includes()
:
💌 Enjoying this post? Subscribe to get more practical dev tips right in your inbox.
Secondly, let’s try indexOf()
:
That’s great, but what should you do if your array’s elements were objects? The easiest way in such a case is to use either find()
or findIndex()
methods.
Firstly, let’s try find()
:
Secondly, let’s try findIndex()
:
Keep in mind, you can use these methods as well if the array's elements were strings or numbers.
In this article, we learned how to add an element to an array only if it did not exist in the given array.
Based on the element types, you can choose the proper way to do so:
- For number or string elements, you can use
new Set()
,includes()
, orindexOf()
. - For object elements, you can use either
find()
orfindIndex()
.
In fact, there are other ways to achieve that goal, however, I introduced just the easiest and the most practical ways.
If you enjoyed this article, I’d truly appreciate it if you could share it—it really motivates me to keep creating more helpful content!
If you’re interested in exploring more, check out these articles.
- 4 Ways To Handle Asynchronous JavaScript
- Is Interface Segregation Principle Redundant?
- MongoDB GridFS, Made Simple
Thanks for sticking with me until the end—I hope you found this article valuable and enjoyable!
Want more dev insights like this? Subscribe to get practical tips, tutorials, and tech deep dives delivered to your inbox. No spam, unsubscribe anytime.