Menü schliessen
Created: October 24th 2024
Last updated: November 12th 2024
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript: How to Only Allow Unique Values in Array

Tags:  guide,  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In JavaScript, arrays allow multiple instances of the same item to be present. To circumvent this, you can use Sets. Under the hood, they are a modification of Maps that will map values as both the key and value, thus forcing every value to be unique, because keys in Maps must be. We recommend you to read our guide on Maps first.


Using Sets

Here is how you declare a Set:

const set = new Set();
const set = new Set([1, 2, 3]);

And here is how you add values to it:

set.add(4);

If you try to add a value that is already included in the set, nothing will happen.

Other than that, usage is virtually identical with Maps.


New Features

Set has recently received some handy Boolean methods. They are Baseline 2024 and available across major browsers since June 2024.

Those include: