Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

removing duplicates from array in javascript

var removeDuplicates = function(nums) {
    for(let i=0; i<nums.length; i++){
        for(let j=i+1; j<nums.length; j++){
            if(nums[i]===nums[j]){
                nums.splice(i,1);
            }
        }
    }
};

this is my code for removing the duplicates, it works for number that are repeated twice but does not work for number that is repeated more than 2. Can anyone please tell me what is wrong here? I want to solve this by only using for loops.
Input: 0,0,1,1,1,2,2,3,3,4
Output: 0,1,1,2,3,4
Expected: 0,1,2,3,4

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • You are removing elements while iterating forwards, so you’ll skip an element each time one is removed (due to the indexes shifting down). Loop backwards instead to delete while iterating.
  • Break out of the inner loop once a matching number is found.
const removeDuplicates = function(nums) {
  for (let i = nums.length - 1; i >= 0; i--) {
    for (let j = 0; j < i; j++)
      if (nums[j] === nums[i]) {
        nums.splice(i, 1);
        break;
      }
  }
};
let arr = [0,0,1,1,1,2,2,3,3,4];
removeDuplicates(arr);
console.log(arr);

Finding the unique elements of an array is much easier to do with a Set:

const uniqueValues = nums =>  [...new Set(nums)];
console.log(uniqueValues([0,0,1,1,1,2,2,3,3,4]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading