Open In App

How to remove multiple elements from array in JavaScript ?

Last Updated : 13 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array containing array elements, the task is to remove multiple elements from the array using JavaScript. The indexes of elements are given that need to be removed from the JavaScript array.

These are the following methods to remove multiple elements from an array in JavaScript:

Approach 1: Using splice() method

  • Store the index of array elements into another array that needs to be removed.
  • Start a loop and run it to the number of elements in the array.
  • Use the splice() method to remove the element at a particular index.  

Example: This example uses the splice() method to remove multiple elements from the array. 

Javascript




const arr = ['Geeks', 'GFG', 'Geek', 'GeeksForGeeks'];
function GFG_Fun() {
    const remove = [0, 2];
 
    for (let i = remove.length - 1; i >= 0; i--)
        arr.splice(remove[i], 1);
 
    console.log(arr);
}
 
GFG_Fun();


Output

[ 'GFG', 'GeeksForGeeks' ]

Approach 2: Using filter() method and indexOf() method

  • Store the index of array elements into another array that needs to be removed.
  • Use the filter() method on the array of elements.
  • Use the indexOf() method to select only those elements which are not present in the indexes array.

Example: This example uses the filter() method and indexOf() method to remove multiple elements from the array. 

Javascript




let arr = ['Geeks', 'GFG', 'Geek', 'GeeksForGeeks'];
 
function GFG_Fun() {
    const indexes = [0, 1];
 
    arr = arr.filter((value, index) => !indexes.includes(index));
 
    console.log(arr);
}
GFG_Fun();


Output

[ 'Geek', 'GeeksForGeeks' ]

Approach 3: Using reduce() and indexOf() method

  • Store the index of array elements into another array that needs to be removed.
  • Use reduce() method on the array of elements.
  • Use the indexOf() method to select only those elements which are not present in the indexes array.

Example: This example uses reduce() method and indexOf() method to remove multiple elements from the array. 

Javascript




let arr = ['Geeks', 'GFG', 'Geek', 'GeeksForGeeks'];
 
function GFG_Fun() {
    const indexes = [0, 1];
 
    arr = arr.reduce((acc, value, index) => {
        if (!indexes.includes(index)) {
            acc.push(value);
        }
        return acc;
    }, []);
 
    console.log(arr);
}
GFG_Fun();


Output

[ 'Geek', 'GeeksForGeeks' ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads