Remove all occurrences of a multiple occurring element in an array 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.

Our function should remove all the values from the array that are repeating. We are required to remove all instances of all such elements.

Example

The code for this will be −

const arr = [1, 2, 3, 2, 4];
const removeAllInstances = (arr = []) => {
   filtered = arr.filter(val => {
      const lastIndex = arr.lastIndexOf(val);
      const firstIndex = arr.indexOf(val);
      return lastIndex === firstIndex;
   });
   return filtered;
};
console.log(removeAllInstances(arr));

Output

And the output in the console will be −

[ 1, 3, 4 ]

Updated on: 23-Nov-2020

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements