Sometimes, we want to push to an array only if value doesn’t exist with JavaScript.
In this article, we’ll look at how to push to an array only if value doesn’t exist with JavaScript.
How to push to an array only if value doesn’t exist with JavaScript?
To push to an array only if value doesn’t exist with JavaScript, we use a set.
For instance, we write
const s = new Set();
s.add("hello");
s.add("world");
s.add("hello");
s.delete("world");
const array = Array.from(s);
to use the Set constructor to create a set.
Then we call add to add entries to it.
And we call delete to delete entries from it.
Next, we call Array.from to convert set s to an array.
Conclusion
To push to an array only if value doesn’t exist with JavaScript, we use a set.