Removing redundant elements from array altogether - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject 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 = [763,55,43,22,32,43,763,43];

The output should be −

const output = [55, 22, 32];

We will be using the following two methods −

  • 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.

Example

Following is the code −

const arr = [763,55,43,22,32,43,763,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

This will produce the following output in console −

[ 55, 22, 32 ]
raja
Published on 18-Sep-2020 16:13:39
Advertisements