Use cases of Sets in JavaScript

We can think of Set as an array but containing only unique values. In general terms ‘a set is a group of unordered unique elements.’

The hash tables are used behind the scene to implement Set. It has a constant time operation of O(1).

Check array contains unique elements:

if we need to check array uniqueness then Set is a good choice. Following is an example of using Set on a char array.

const arr = ['a', 'a', 'b', 'c', 'c'];
const setObject = new Set(arr);
console.log(setObject);

// Output
Set(3) {'a', 'b', 'c'}

We can check an array contains unique elements or not using the following functions:

const hasDuplicateArrEelements = (originalArr) => {
    const newArr = new Set(originalArr);
    return newArr.size === originalArr.length;
};

const arr = ['a', 'a', 'b', 'c', 'c'];
console.log(hasDuplicateArrEelements(arr));

// Output
false