Sometimes, we want to use array push() to insert unique items with JavaScript.
In this article, we’ll look at how to use array push() to insert unique items with JavaScript.
How to use array push() to insert unique items with JavaScript?
To use array push() to insert unique items with JavaScript, we can use a set.
For instance, we write
const items = new Set();
items.add(item);
console.log([...items]);
to create a new set with the Set
constructor.
Then we call add
to add a new item
to the set.
Sets can’t have duplicate items, so only the last one with the same value is kept.
And then we can use the spread operator to convert items
back to an array.
Conclusion
To use array push() to insert unique items with JavaScript, we can use a set.