Javascript Add to Array if not Exist

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 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.

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

💌 Enjoying this post? Subscribe to get more practical dev tips right in your inbox.

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

  1. For number or string elements, you can use new Set(), includes(), or indexOf().
  2. For object 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 most practical ways.

Think about it

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.

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top