How to Find Duplicates in an Array in JavaScript?

Estimated read time 2 min read

To find duplicates in an array in JavaScript, you can use an object or a Set to keep track of the unique values in the array. If a value is already in the object or Set, it is a duplicate.

Here’s an example using an object:

function findDuplicates(arr) {
  let duplicates = [];
  let seen = {};
  for (let i = 0; i < arr.length; i++) {
    if (seen[arr[i]]) {
      duplicates.push(arr[i]);
    } else {
      seen[arr[i]] = true;
    }
  }
  return duplicates;
}

let arr = [1, 2, 3, 4, 5, 1, 2, 6, 7];
let duplicates = findDuplicates(arr);
console.log("Duplicates: " + duplicates);

Here’s an example using a Set:

function findDuplicates(arr) {
  let duplicates = [];
  let seen = new Set();
  for (let i = 0; i < arr.length; i++) {
    if (seen.has(arr[i])) {
      duplicates.push(arr[i]);
    } else {
      seen.add(arr[i]);
    }
  }
  return duplicates;
}

let arr = [1, 2, 3, 4, 5, 1, 2, 6, 7];
let duplicates = findDuplicates(arr);
console.log("Duplicates: " + duplicates);

In both examples, the findDuplicates function takes an array arr as an argument. The function uses an object seen or a Set seen to keep track of the unique values in the array. If a value is already in the object or Set, it is a duplicate and is pushed into the duplicates array. The function then returns the duplicates array. The code then calls the findDuplicates function with the arr value and logs the result to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply