Finding Duplicate Values in an Array

In this tutorial, we will explore various methods to find duplicate values in a JavaScript array. This is a common problem that can be solved using different approaches, including sorting, looping, and utilizing built-in array methods.

Introduction to the Problem

Given an array of elements, our goal is to identify the values that appear more than once. For example, if we have the array [1, 2, 3, 1, 3, 1], the duplicate values are 1 and 3.

Method 1: Sorting and Looping

One way to find duplicates is by sorting the array first and then iterating through it to compare adjacent elements. If two adjacent elements are equal, it means we’ve found a duplicate.

function findDuplicates(arr) {
  let sortedArr = arr.slice().sort();
  let results = [];
  for (let i = 0; i < sortedArr.length - 1; i++) {
    if (sortedArr[i + 1] === sortedArr[i]) {
      results.push(sortedArr[i]);
    }
  }
  return results;
}

let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);

Method 2: Using Reduce and IndexOf

Another approach involves using the reduce method to iterate through the array and check for duplicates using indexOf. If an element’s index is not equal to its first occurrence, it’s a duplicate.

function findDuplicates(arr) {
  return arr.reduce((acc, el, i, arr) => {
    if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el);
    return acc;
  }, []);
}

let input = [1, 2, 3, 1, 3, 1];
console.log(findDuplicates(input)); // Output: [1, 3]

Method 3: Utilizing Sets

We can also leverage the Set data structure to find duplicates. By reducing the array into a set and then filtering out unique elements, we can identify duplicates.

function findDuplicates(arr) {
  return Array.from(arr.reduce((acc, v, i, arr) => {
    return arr.indexOf(v) !== i ? acc.add(v) : acc;
  }, new Set()));
}

let input = [1, 2, 3, 1, 3, 1];
console.log(findDuplicates(input)); // Output: [1, 3]

Method 4: Using Filter and IndexOf

Another concise method involves using filter to find elements that have an index not equal to their first occurrence.

function findDuplicates(arr) {
  return [...new Set(arr.filter((e, i, a) => a.indexOf(e) !== i))];
}

let input = [1, 2, 3, 1, 3, 1];
console.log(findDuplicates(input)); // Output: [1, 3]

Conclusion

Finding duplicate values in an array is a common task that can be accomplished using various methods. Each method has its own trade-offs in terms of performance and readability. By understanding these different approaches, you can choose the best one for your specific use case.

Leave a Reply

Your email address will not be published. Required fields are marked *