Remove element from array referencing spreaded array in JavaScript


Suppose we have an array of literals like this −

const arr = ['cat','dog','elephant','lion','tiger','mouse'];

We are required to write a JavaScript function that takes in one such array as the first argument and then any number of strings as second and third and many more arguments.

Then our function should remove all the strings from the array taken as first argument in place if that string is provided as argument to the function.

Example

The code for this will be −

const arr = ['cat','dog','elephant','lion','tiger','mouse'];
const removeFromArray = (arr, ...removeArr) => {
   removeArr.forEach(item => {
      const index = arr.indexOf(item);
      if(index !== -1){
         arr.splice(index, 1);
      };
   });
}
removeFromArray(arr, 'dog', 'lion');
console.log(arr);

Output

The output in the console −

[ 'cat', 'elephant', 'tiger', 'mouse' ]

Updated on: 12-Oct-2020

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements