Finding all duplicate numbers in an array with multiple duplicates in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers that contains many duplicate entries.

The function should prepare an array of all the elements that appear more than once in the array and return that array.

For example −

If the input array is −

const arr = [1, 3, 4, 3, 5, 4, 6, 8, 8];

Then the output array should be −

const output = [3, 4, 8];

Example

Following is the code −

const arr = [1, 3, 4, 3, 5, 4, 6, 8, 8];
const findDuplicates = (arr = []) => {
   let map = {};
   let res = [];
   for(let i = 0; i < arr.length; i++) {
      if(map[arr[i]]) {
         if(map[arr[i]] === 1) {
            res.push(arr[i]);
         }
         map[arr[i]] = map[arr[i]] + 1;
      } else {
         map[arr[i]] = 1;
      };
   };
   return res;
};
console.log(findDuplicates(arr));

Output

Following is the output on console −

[3, 4, 8]
raja
Published on 10-Dec-2020 08:07:36
Advertisements