Check if an array contains duplicate values, without using arrays

Do you want to write a javascript or typescript function which checks if an array contains duplicate values or not? And without using any array iterations in your function?

There is an easy solution for that and that is Set.

The Set allows you to store unique values of any type, it could be either primitives (Numbers, Strings, and, Boolean) or Objects.

So let’s create a Set.

let s = new Set();
s.add(1);
s.add(1);
s.add(2);
s.add(3);
s.add(4);
s.add(4);

Now, your Set hold all the elements you have provided.

console.log(s);

Your console will emit value like this. Look closely, we have added 5 items in our array with last two items as duplicates. The Set will eliminate duplicates.

Set(4) {1, 2, 3, 4}
size: (...)
__proto__: Set
[[Entries]]: Array(4)
0: 1
1: 2
2: 3
3: 4
length: 4

Let’s find out how to check for uniqueness

let isUniq;

isUniq = (myUniqArr.length === new Set(myUniqArr).size);
console.log(`${myUniqArr} is unique : ${isUniq}`);

isUniq = (myNonUniqArr.length === new Set(myNonUniqArr).size);
console.log(`${myNonUniqArr} is unique : ${isUniq}`);

In the above code, we are checking for two types of array’s, one with unique values and the other one is non unique.

If there is any duplicates, the Set class will ignore the duplicates and returns the size or length of an array. By checking the length, we can make sure if an array is unique or non unique.

 

For browser compatibility, check the below link;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#Browser_compatibility

 

 

 

ALSO READ  Minify / Uglify / remove comments your final Angular build