How to find duplicate items in array 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:
let sortedArr = arr.sort();
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 find duplicate items in array and 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: