How to check if a JavaScript array has duplicate elements

Here’s a one-liner for checking if an array contains any duplicate scalar values.

const hasDuplicates = arr => {
  return new Set(arr).size !== arr.length

This works by first converting the given array to a Set – a data structure containing only unique values. We then check whether the number of unique elements in the set is equal to the total number of elements in the array.

If they aren’t equal, then the array must have at least one duplicate because when converting it to a set, we lost some elements (the set removes any duplicate elements).

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: