JavaScript, how to find duplicates in an array
How to find and remove duplicates in a JavaScript array
If you want to remove the duplicates, there is a very simple way, making use of the Set data structure provided by JavaScript. It’s a one-liner:
const yourArrayWithoutDuplicates = [...new Set(yourArray)]
To find which elements are duplicates, you could use this “array without duplicates” we got, and and remove 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, and then check if the “next item” is same to the current item, and put it into an 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 works for primitive values, not objects. In the case of objects, you need a way to compare them.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025