Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to splice duplicate item in array

I am making an attempt at writing a function in JavaScript that accepts an array that has duplicates in it and returns the same array removing duplicates. I know how to this using a Set, filter and reduce but I wanted to try to do it without using those functions. The problem is that I don't know how to splice the duplicate item once I have found them, so how can I just remove the item from the array if it is found as a duplicate, here is my code:

function clearDuplicatesInArray(arr, item) {
 for(i = 0; i < arr.length; i++) {
   for(j = 0; j < arr.length; j++) {
      if(arr[i] === arr[j]) {
       arr.splice(arr[i], arr[j])
      }
    }
  }
 return arr;
}

clearDuplicatesInArray([1,1,2,3]);
like image 533
Mahma Deva Avatar asked Oct 22 '19 08:10

Mahma Deva


2 Answers

You could iterate form the end, to prevent slicing for indices whixh are not visited yet and use a second loop until the outer index, because over this index, you have already visited the items.

For splicing, take the index and one as parameter, which removes one element at the given index.

function clearDuplicatesInArray(array, item) {
    var i = array.length,
        j;
    
    while (--i) {
        for (j = 0; j < i; j++) {
            if (array[i] === array[j]) {
                array.splice(i, 1);
                break;
            }
        }
    }
    return array;
}

console.log(clearDuplicatesInArray([1, 1, 2, 3]));
like image 68
Nina Scholz Avatar answered Oct 06 '22 00:10

Nina Scholz


I am just going to fix your code, although you can get the solution in many different ways.

function clearDuplicatesInArray(arr, item) {
 for(i = 0; i < arr.length; i++) {
   for(j = i+1; j < arr.length; j++) {
      if(arr[i] === arr[j]) {
       arr.splice(i, 1);
       i--;
       break;
      }
    }
  }
 return arr;
}

console.log(clearDuplicatesInArray([1,1,2,3]));
like image 34
Amit Avatar answered Oct 06 '22 00:10

Amit