Reputation: 1512
It's a bit fuzzy for me, but I'm trying to create a simple function that takes an array and some arguments and removes the arguments from the array.
For example if I have an array such as [1,2,3,4]
and the arguments 2,3
it would return [1,4]
as a result.
This is what I have so far:
const removeFromArray = (arr) => {
let args = Array.from(arguments);
return arr.filter(function (item) {
!args.includes(item);
});
}
It doesn't work though. It works if I want to remove all the items from the array, but doesn't if I only go for specific ones.
How can I make this work so that it works even if I'm supplying an argument that is not part of the array (I want it to ignore those) and also if I have strings in the array as well?
Thanks in advance!
Upvotes: 1
Views: 98
Reputation: 126
Add a second parameter for the items you want to have removed.
const removeFromArray = (arr, toBeRemoved) => {
return arr.filter(item => !toBeRemoved.includes(item));
}
Example call:
const array = [1, 2, 3, 4]
const newArray = removeFromArray(arr, [2, 3])
console.log(newArray) // [1, 4]
Upvotes: 0
Reputation: 3471
Stick it to the Array.prototype
, might use it somewhere else
Array.prototype.remove = function(...args) {
return this.filter(v => !args.includes(v));
}
Upvotes: -1
Reputation: 33726
In arrow functions the implicit object arguments
doesn't exist, so declare the function using the keyword function
, likewise, you need to return the result of the function includes
within the handler of the function filter
.
const removeFromArray = function() {
let [arr, ...args] = Array.from(arguments);
return arr.filter(function (item) {
return !args.includes(item);
});
}
console.log(removeFromArray([1,2,3,4], 2, 3));
Upvotes: 2
Reputation: 386550
You could take rest parameters ...
for the items to exclude the values.
const removeFromArray = (array, ...items) => array.filter(item => !items.includes(item));
console.log(removeFromArray([1, 2, 3, 4], 1, 4))
To use you style, you need to exclude the first item of arguments
, because this is the array with all items.
let args = Array.from(arguments).slice(1);
// ^^^^^^^^^
Upvotes: 4