Find the Duplicate Elements in the Array

Find the Duplicate Elements in the Array

Hey Coders, Today in this article I'll going to tell you How to find the Duplicate Elements of the array using various methods of JavaScript. 
All of these methods will find and return an array containing the duplicate elements from the input array. You can choose the method that suits your requirements and coding style best.

Method 1: Using Nested Loops


function findDuplicates(arr) {
  const duplicates = [];

  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j] && !duplicates.includes(arr[i])) {
        duplicates.push(arr[i]);
        break;
      }
    }
  }

  return duplicates;
}

const arr = [1, 2, 3, 4, 2, 5, 6, 1];
const duplicates = findDuplicates(arr);

console.log(duplicates); // Output: [1, 2]

Method 2: Using a Hash Map


function findDuplicates(arr) {
  const countMap = {};
  const duplicates = [];

  for (const element of arr) {
    countMap[element] = (countMap[element] || 0) + 1;
  }

  for (const element in countMap) {
    if (countMap[element] > 1) {
      duplicates.push(Number(element));
    }
  }

  return duplicates;
}

const arr = [1, 2, 3, 4, 2, 5, 6, 1];
const duplicates = findDuplicates(arr);
console.log(duplicates); // Output: [1, 2]


Method 3: Using the Set data structure


function findDuplicates(arr) {
  const uniqueSet = new Set();
  const duplicatesSet = new Set();

  for (const element of arr) {
    if (uniqueSet.has(element)) {
      duplicatesSet.add(element);
    } else {
      uniqueSet.add(element);
    }
  }

  return Array.from(duplicatesSet);
}

const arr = [1, 2, 3, 4, 2, 5, 6, 1];
const duplicates = findDuplicates(arr);
console.log(duplicates); // Output: [1, 2]

Method 4: Using the filter() method


function findDuplicates(arr) {
  return arr.filter((element, index) => arr.indexOf(element) !== index);
}

const arr = [1, 2, 3, 4, 2, 5, 6, 1];
const duplicates = findDuplicates(arr);

console.log(duplicates); // Output: [1, 2]

Method 5: Using the reduce() method

function findDuplicates(arr) {
  const countMap = arr.reduce((map, element) => {
    map[element] = (map[element] || 0) + 1;
    return map;
  }, {});

  return Object.keys(countMap).filter((element) => countMap[element] > 1).map(Number);
}

const arr = [1, 2, 3, 4, 2, 5, 6, 1];
const duplicates = findDuplicates(arr);

console.log(duplicates); // Output: [1, 2]


Comments

Popular posts from this blog

Download Kiran Publication Math Book PDF for SSC, Railway, and Banking Exams

Careerwill Gagan Pratap Sir Maths Book Pdf

THREE.RGBELoader is not a constructor: error solved

Contact form

Name

Email *

Message *