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: 2020-11-23T10:58:28+05:30

756 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements