Find duplicate element in JavaScript Array

How to find and remove duplicate items from javascript array!

let numberArray = [9, 7, 1, 4, 1, 2, 3, 9, 5, 4, 5, 7, 10, 4];

Look at the above array, which has some duplicate number, we need to remove all duplicate numbers.

There is no built-in methods like distinct, so we need to write a method to search and remove all duplicate items.

Here are the steps:

  • First, we sort the array. let sortedArr = arr.sort();
  • The loop through each item to compare if earlier item is same as current item, if yes, then consider as duplicate item.
  • Add all duplicate items in a new array.
  • Then based on duplicate item array, remove all duplicate elements from original array.
  • While adding each element in duplicate list, make sure the item is not already added there; otherwise, we end up adding duplicate item again there, so there has to be an additional check in the code below.
    const found = duplicateItems.find(v=> v==sortedArr[i]);
    if(found==null){
        duplicateItems.push(sortedArr[i]);
    }    
    

Here is how the code will look like, the method will take an array as parameter then return an array of duplicate items.

const getDuplicates = (arr) => {
let sortedArr = arr.sort(); console.log(sortedArr); let duplicateItems = [];
for (let i = 0; i < sortedArr.length - 1; i++) {
if (sortedArr[i + 1] == sortedArr[i]) {
// check if the item is already added.
const found = duplicateItems.find(v=> v==sortedArr[i]);
            if(found==null){
              duplicateItems.push(sortedArr[i]);
            }        
      }
    }
    return duplicateItems;
  }

Now, we need to call the above methods with one array to see if the output result is correct.

let numberArray = [9, 7, 1, 4, 1, 2, 3, 9, 5, 4, 5, 7, 10, 4];
console.log(getDuplicates(numberArray));

The above call returing an array of [ 1, 4, 5, 7, 9 ], these are duplicate number in the above array.

Now you may have a question whether the above function will work for a string array or not, let’s try calling with a string array.

let cities = ["Mumbai", "Pune", "Kolkata", "Goa","Delhi","Goa", "Ludhiana", "Pune", "Nagpur", "Durgapur"];
console.log(getDuplicates(cities));

Yes, the above call perfectly returned an array of [ 'Goa', 'Pune' ].

But there is catch, javascript is case sensitive, "Goa" and "goa" is not the same string, so to make it work perfectly, we should convert the string in either case (preferably to lower case), that will require one minor changes in above code.

You may be interested in following posts:

 
Advanced JavaScript
Find duplicate Item in Javascript Array
javascript Interview Questions Answers
JavaScript Examples | JavaScript Online Course