In this quick tutorial, you’ll learn how to find duplicates in an array using JavaScript. For finding duplicate values in JavaScript array, you’ll make use of the traditional for loops and Array reduce method.
Using For Loop
Let’s see how you can find duplicates in an array using for loop. The logic is you’ll separate the array into two array, duplicate array and unique array. You’ll iterate over the values in the array and push the items into unique list if it already doesn’t exist. It it already exists you have found a duplicate and hence push it into duplicate array. Let’s have a look at the code.
// Find duplicates using for loop
let item_list = [1,2,3,4,5,5,5,7,8,2,3,4,4,4,4,4];
let unique_list = [];
let duplicate_list = [];
function check_insert_unique(item){
if(unique_list.includes(item)){
if(duplicate_list.indexOf(item) == -1){
duplicate_list.push(item)
}
} else {
if(unique_list.indexOf(item) == -1){
unique_list.push(item)
}
}
}
for(let i = 0; i < item_list.length; i++){
check_insert_unique(item_list[i]);
}
console.log('Duplicate items are ' + duplicate_list.join(','));
Using Reduce Method
Another alternate method to find duplicate values in an array using JavaScript is using reduce method. Using reduce method you can set the accumulator parameter as an empty array. On each iteration check if it already exists in the actual array and the accumulator array and return the accumulator. Here is how the code looks:
// Find duplicates using for loop
let item_list = [1,2,3,4,5,5,5,7,8,2,3,4,4,4,4,4];
let duplicate = item_list.reduce((acc,currentValue,index, array) => {
if(array.indexOf(currentValue)!=index && !acc.includes(currentValue)) acc.push(currentValue);
return acc;
}, []);
console.log('Duplicate items are ' + duplicate.join(','));
Wrapping It Up
In this short tutorial, you learnt about two ways to find duplicate values in JavaScript array. One method involved the use of for loop and another method used the Array reduce method.
Have you ever encountered this issue and did solve it using any other method ? Do let us know your thoughts in the comments below.