Removing duplicates and keep one instance in JavaScript


We are required to write a JavaScript function that takes in an array of literal values. The array might contain some repeating values inside it.

Our function should remove all the repeating values keeping the first instance of repeating value in the array.

Example

The code for this will be −

const arr = [1, 5, 7, 4, 1, 4, 4, 6, 4, 5, 8, 8];
const deleteDuplicate = (arr = []) => {
   for(let i = 0; i < arr.length; ){
      const el = arr[i];
      if(i !== arr.lastIndexOf(el)){
         arr.splice(i, 1);
      }
      else{
         i++;
      };
   };
};
deleteDuplicate(arr);
console.log(arr);

Output

And the output in the console will be −

[ 7, 1, 6, 4, 5, 8 ]

Updated on: 23-Nov-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements