If the element repeats, remove all its instances from array in 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];

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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

[ 55, 22, 32 ]
raja
Published on 20-Oct-2020 11:46:18
Advertisements