Completely removing duplicate items from an array in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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 ]
raja
Published on 19-Aug-2020 07:07:43
Advertisements