Reputation: 3
I'm trying to change this one:
const removeElements = (arr, callback) => {
for(var i = 0; i < arr.length; i++){
callback(arr[i], arr);
}
return arr;
};
To a forEach like this:
const removeWithForEach = (arr, callback) => {
arr.forEach(callback(arr.value, arr));
};
But it's not working. Would you guys help?
Upvotes: 0
Views: 62
Reputation: 386560
Why not change the signature of callback
to
const callback = (element, index, array) => { /* code */ };
// ^^^^^^ add this parameter
and use the calback directly ind Array#forEach
const removeWithForEach = (arr, callback) => arr.forEach(callback);
Upvotes: 1
Reputation: 370689
You're currently calling the callback
immediately, before forEach
is invoked. Pass a function reference to forEach
instead:
const removeWithForEach = (arr, callback) => {
arr.forEach((value) => {
callback(value, arr);
});
return arr;
};
(though it would make more sense just to use Array.prototype.forEach
instead of removeWithForEach
)
Upvotes: 4