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 just if it didn’t exist beforehand and ignore the process if it already existed.
So, how can we achieve this goal? I think while you landed 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()
:
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 knew how to add an element to an array just if it did not exist in the given array.
Based on the elements types you can choose the proper way to do so:
- For numbers or strings elements, you can use
new Set()
,includes()
, orindexOf()
. - For objects 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 more practical ways.
If you liked this article please rate and share it to spread the word, really, that encourages me a lot to create more content like this.
If you found this article useful, check out these articles as well:
- 4 Ways To Handle Asynchronous JavaScript
- Is Interface Segregation Principle Redundant?
- MongoDB GridFS, Made Simple
Thanks a lot for staying with me up till this point. I hope you enjoy reading this article.