Categories
JavaScript Answers

How to prevent adding duplicate keys to a JavaScript array?

Spread the love

To prevent adding duplicate keys to a JavaScript array, we use sets.

For instance, we write

const set = new Set();
set.add(1);
set.add(2);
set.add(3);

console.log(set);

to create a new set with the Set constructor.

Then we call add to add the entries into the set.

Duplicate entries won’t be added to the set with add.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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