sajad torkamani

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).

Tagged: JavaScript