Ehsan
Ehsan

Reputation: 3

Can't change a for loop to forEach

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

Answers (2)

Nina Scholz
Nina Scholz

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

CertainPerformance
CertainPerformance

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

Related Questions