[英]Removing Values from an Array using the Filter Method
Given an array and subsequent unknown number of arguments, how can I remove all elements from the initial array that are of the same value as these arguments? 给定一个数组和后续未知数量的参数,如何从初始数组中删除与这些参数具有相同值的所有元素? This is what I have so far:
这是我到目前为止的内容:
function destroyer(arr) {
var arrayOfArgs = [];
var newArray = [];
for (var i = 0; i < arguments.length; i++) {
newArray = arr.filter(function (value) {
return value !== arguments[i + 1];
});
}
return newArray;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
You can use Array#filter
with arrow function Array#includes
and rest parameters . 您可以将
Array#filter
与箭头函数Array#includes
和rest参数一起使用 。
function destroyer(arr, ...remove) {
return arr.filter(e => !remove.includes(e));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
function destroyer(arr, ...remove) { return arr.filter(e => !remove.includes(e)); } var updatedArr = destroyer([1, 2, 3, 1, 2, 3], 2, 3); console.log(updatedArr);
Equivalent Code in ES5: ES5中的等效代码:
function destroyer(arr) {
var toRemove = [].slice.call(arguments, 1);
return arr.filter(function(e) {
return toRemove.indexOf(e) === -1;
});
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
function destroyer(arr) { var toRemove = [].slice.call(arguments, 1); return arr.filter(function (e) { return toRemove.indexOf(e) === -1; }); } console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Use rest parameters to specify the subsequent arguments, Array.prototype.filter()
with an arrow function to filter the arr
, and Array.prototype.includes()
to determine whether args
contains specific item. 使用rest参数指定后续参数,使用带有箭头函数的
Array.prototype.filter()
过滤arr
,并使用Array.prototype.includes()
确定args
是否包含特定项目。
function destroyer(arr, ...args) {
return arr.filter(x=> !args.includes(x))
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.