Javascript Add to Array if not Exist
0 0 votes
Article Rating

JavaScript: Add To Array Just If Element Doesn’t Exist

In JavaScript, how to add an element to an array just if it does not yet exist within the given array or ignore the process if it already exists?

Introduction

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.

Set()

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 numbersSet is the easiest way to achieve your goal.

includes() or indexOf()

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():

find() or findIndex()

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.

Conclusion

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:

  1. For numbers or strings elements, you can use new Set(), includes(), or indexOf().
  2. For objects elements, you can use either find() or findIndex().

In fact, there are other ways to achieve that goal, however, I introduced just the easiest and the more practical ways.

Think about it

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 my content helpful, it is a good idea to subscribe to my newsletter. Make sure that I respect your inbox so I'll never spam you, and you can unsubscribe at any time!

If you found this article useful, check out these articles as well:

Thanks a lot for staying with me up till this point. I hope you enjoy reading this article.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Scroll to Top