JavaScript: check if a linear array contains duplicate elements

JavaScript: check if a linear array contains duplicate elements

In this article we will see how to check if a linear array contains duplicate elements in JavaScript.

In this article we will see how to check if a linear array contains duplicate elements in JavaScript.

By converting the array into a Set object we eliminate any duplicate elements and thus compare the number of its elements with that of the original array. If that number doesn't match, the array contains duplicate elements.


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