Completely removing duplicate items from an array in JavaScript



We are required to write a function that takes in an array and returns a new array that have all duplicate values removed from it.

The values that appeared more than once in the original array should not even appear for once in the new array.

For example, if the input is βˆ’

const arr = [23,545,43,232,32,43,23,43];

The output should be βˆ’

const output = [545, 232, 32];

Understanding the difference βˆ’

  • Array.prototype.indexOf() β†’ It returns the index of first occurrence of searched string if it exists, otherwise -1.

  • Array.prototype.lastIndexOf() β†’ It returns the index of last occurrence of searched string if it exists, otherwise -1.

Both methods start from left to right.

Both methods start from 0 if second argument is undefined, other start from the second argument if it’s a number.

So the vital point here is, if in an array, the indexOf() and lastIndexOf() method point to the same index, we can sure that it only exists once, so we will use this finding in our code.

The full code for the function will be βˆ’

Example

const arr = [23,545,43,232,32,43,23,43];
const deleteDuplicate = (arr) => {
   const output = arr.filter((item, index, array) => {
      return array.indexOf(item) === array.lastIndexOf(item);
   })
   return output;
};
console.log(deleteDuplicate(arr));

Output

The output in the console will be βˆ’

[ 545, 232, 32 ]
Updated on: 2020-08-19T07:07:57+05:30

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements