JavaScript 如何从数组中删除多个元素
给定一个包含数组元素的数组,并且任务是使用JavaScript从数组中删除多个元素。给定需要从JavaScript数组中删除的元素的索引。
以下是在JavaScript中从数组中删除多个元素的方法:
- 使用splice()方法
- 使用filter()方法和indexOf()方法
- 使用reduce()和indexOf()方法
方法1:使用splice()方法
- 将数组元素的索引存储在另一个需要被删除的数组中。
- 开始循环并运行到数组中元素的数量。
- 使用splice()方法删除特定索引处的元素。
示例: 此示例使用splice()方法从数组中删除多个元素。
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();
输出
[ 'GFG', 'GeeksForGeeks' ]
方法2:使用filter()方法和indexOf()方法
- 将数组元素的索引存储到另一个需要被移除的数组中。
- 对元素数组使用 filter()方法 。
- 使用 indexOf()方法 选择那些不在索引数组中存在的元素。
示例: 此示例使用filter()方法和indexOf()方法从数组中移除多个元素。
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();
输出
[ 'Geek', 'GeeksForGeeks' ]
方法3:使用 reduce() 方法和 indexOf() 方法
- 将数组元素的索引存储到另一个需要被移除的数组中。
- 对元素数组使用 reduce() 方法。
- 使用 indexOf() 方法,只选择那些不在索引数组中存在的元素。
示例: 这个示例使用 reduce() 方法和 indexOf() 方法从数组中移除多个元素。
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();
输出
[ 'Geek', 'GeeksForGeeks' ]
极客教程