How to prevent adding duplicate keys to a JavaScript array?

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.