Menu Close

How to find duplicates in an array using javascript

Find duplicate array

In this topic, When we working with arrays in JavaScript, it is common to encounter duplicate values. Duplicate values can cause problems in some cases, such as when performing calculations or comparisons on the array. Fortunately, JavaScript provides lot of methods to identify and remove duplicate values from an array. Here is the  several Method to find duplicate values in a JavaScript array:

Using indexOf() Method

const arr = [1, 2, 3, 4, 2, 5, 1];

const duplicates = [];

for (let i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== i) {
duplicates.push(arr[i]);
}
}
console.log(duplicates);
// Output: [1, 2]; 

Using filter() Method

const array = [1, 2, 3, 4, 5, 5, 3, 6, 7];

const duplicates = array.filter(
(value, index) => array.indexOf(value)!== index);

console.log(duplicates);

// Output: [5, 3] 

In above example, The filter() method allows you to create a new array that contains only the elements that pass a certain test. By using the filter method with a callback function that checks for duplicate elements, you can easily find the duplicates in an array.

Posted in JavaScript, Web Technologies

You can also read...