0

I am trying to find the dupicates in an array and removing them at the duplicated index using the splice method, the code is removing the duplicates but it still leaves one duplicated item.

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


console.log(removeDuplicates([1,2,2,2,2,2,2]))

enter image description here

1
  • 2
    Try using Set, [...new Set([1,2,2,2,2,2,2])] Commented Apr 18, 2021 at 4:55

2 Answers 2

1

The problem is you're looping in forward direction and simultaneously removing elements, which messes up the indices.

So, you should loop in backwards direction in this case.

var removeDuplicates = function (nums) {
  let length = nums.length;
  for (let i = length - 1; i >= 0; i--) {
    console.log(`All redundant instances of ${nums[i]} will be removed`);
    for (let j = i - 1; j >= 0; j--) {
      if (nums[i] == nums[j]) {
        nums.splice(j, 1);
      }
    }
    console.log(JSON.stringify(nums));
  }
  return nums;
};

const result = removeDuplicates([1, 1, 2, 3, 3, 2]);
console.log("Final Result", JSON.stringify(result));

For removing duplicates I would always prefer using a Set.

const 
  arr = [1, 1, 2, 3, 3, 2],
  result = [...new Set(arr)]

console.log(JSON.stringify(result))

Sign up to request clarification or add additional context in comments.

1 Comment

@prmdpsn56 Please check if this solves your problem. Let me know if you have any issues.
0

There are different ways to remove array duplicates.

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

let unique = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

let x = (names) => names.filter((v,i) => names.indexOf(v) === i)
x(names); // 'John', 'Paul', 'George', 'Ringo'
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

function removeDups(names) {
  let unique = {};
  names.forEach(function(i) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

removeDups(names); // // 'John', 'Paul', 'George', 'Ringo'

https://wsvincent.com/javascript-remove-duplicates-array/

https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.