JavaScript: How to Check if an Array has Duplicate Values

When dealing with arrays in JavaScript, we sometimes need to find out if the array contains duplicate values. Unfortunately, JavaScript arrays do not expose any built-in methods that can do this for us -- we have to write the implementation ourselves.

One approach to this problem might look like this:

function checkForDuplicates(array) {
let valuesAlreadySeen = []
for (let i = 0; i < array.length; i++) {
let value = array[i]
if (valuesAlreadySeen.indexOf(value) !== -1) {
return true
}
valuesAlreadySeen.push(value)
}
return false
}

This works, but in the worst case scenario where the only duplicate value occurs at the end of the array, this is not a very performant approach. We would have to iterate through the entire array (which could be huge) only to realize at the last element that there is a duplicate value in the array.

Another approach that I recently learned uses ES6 Sets.

In case you aren't familiar with Sets in JavaScript (I wasn't until recently!), here is the MDN definition:

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.

Read that last line one more timethat's our secret sauce here. 'A value in the Set may only occur once; it is unique in the Set's collection.'

This means that we can convert our array into a Set and be confident that it only contains unique values. Once we've extracted all of the unique values from the array and stored them in our Set, we can compare the length of the array to the length of the Set. If the lengths are not equal, then the array contained duplicate values.

Here's what that approach looks like:

function checkForDuplicates(array) {
return new Set(array).size !== array.length
}

If the length of the Set and the array are not the same this function will return true, indicating that the array contained duplicates. Otherwise, if the array and the Set are the same length the function will return false and we can be certain that the original array contained no duplicate values.

I really like this second approach because of how concise and expressive it is, but you might run into browser support issues if you need to target older browsers, so take that into consideration.

Now What?

If you enjoyed this post, I'd love to continue the conversation on Twitter.

Social media not your thing? Shoot me an email: will@willharris.dev

Designed and developed by Will Harris

Built with

Hosted on

Social

Twitter

GitHub

LinkedIn