Reputation: 2583
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);
Upvotes: 0
Views: 52
Reputation: 92521
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.
function destroyer(arr, ...args) {
return arr.filter(x=> !args.includes(x))
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3))
Upvotes: 1
Reputation: 87203
You can use Array#filter
with arrow function Array#includes
and rest parameters.
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:
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));
Upvotes: 1