Given an array containing array elements and 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:
- 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' ]
- 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' ]
- 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' ]