How to splice duplicate item in array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have an array of Number / String literals that contain some duplicate values, we have to remove these values from the array without creating a new array or storing the duplicate values anywhere else.

We will use the Array.prototype.splice() method to remove entries inplace, and we will take help of Array.prototype.indexOf() and Array.prototype.lastIndexOf() method to determine the duplicacy of any element.

Example

const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5];
arr.forEach((el, ind, array) => {
   if(array.indexOf(el) !== array.lastIndexOf(el)){
      array.splice(ind, 1);
   }
});
console.log(arr);

Output

The output in the console will be −

[
   4, 1, 5, 2,
   6, 8, 7
]
raja
Published on 21-Aug-2020 13:41:10
Advertisements