JavaScript, how to find duplicates in an array

How to find and delete duplicates in JavaScript array

If you want to delete duplicates, you can use the Set data structure provided by JavaScript, which is a very simple method. This is one-liner:

const yourArrayWithoutDuplicates = [...new Set(yourArray)]

To find which elements are duplicates, you can use the "array without duplicates" we get, and then delete each item it contains from the original array content:

const yourArray = [1, 1, 2, 3, 4, 5, 5]

const yourArrayWithoutDuplicates = […new Set(yourArray)]

let duplicates = […yourArray] yourArrayWithoutDuplicates.forEach((item) => { const i = duplicates.indexOf(item) duplicates = duplicates .slice(0, i) .concat(duplicates.slice(i + 1, duplicates.length)) })

console.log(duplicates) //[ 1, 5 ]

Another solution is to sort the array, then check if the "next item" is the same as the current item, and then put it in the array:

const yourArray = [1, 1, 2, 3, 4, 5, 5]

let duplicates = []

const tempArray = […yourArray].sort()

for (let i = 0; i < tempArray.length; i++) { if (tempArray[i + 1] === tempArray[i]) { duplicates.push(tempArray[i]) } }

console.log(duplicates) //[ 1, 5 ]

Note that this only applies to original values, not to objects. For objects, you need a way to compare them.

Download mine for freeJavaScript beginner's manual


More js tutorials: