EN
JavaScript - find duplicates in array
0
points
In this article, we would like to show you how to find duplicates in array using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const array = [1, 2, 3, 2, 3, 3];
const sortedArray = array.slice().sort();
let result = [];
for (let i = 0; i < sortedArray.length - 1; ++i) {
if (sortedArray[i + 1] === sortedArray[i]) {
result.push(sortedArray[i]);
}
}
console.log('Duplicate elements: ' + result);
Practical example
In this example, we create a reusable arrow function that sorts the array
and then checks if the next item in the array is the same as the previous one to find the duplicates
.
// ONLINE-RUNNER:browser;
const findDuplicates = (array) => {
const sortedArray = array.slice().sort();
let results = [];
for (let i = 0; i < sortedArray.length - 1; ++i) {
if (sortedArray[i + 1] === sortedArray[i]) {
results.push(sortedArray[i]);
}
}
return results;
}
// Usage example:
const numbers = [1, 2, 3, 2, 3, 3];
const duplicates = findDuplicates(numbers);
console.log('Duplicate elements: ' + duplicates);