0

function addToArr(num, arr) {
  arr.push(num);
}
theArr = [1, 2, 3, 4];
myArr = [];
theArr.forEach(addToArr(ele, theArr));

console.log(myArr);

I wanted to write a function that could be used in a forEach() that could take a different array as a parameter - that I could push to.

2 Answers2

3

The parameter you pass to forEach must be a function, meaning your addToArr needs to return a function. This is often called currying, partial application, or a closure.

function addToArr(arr) {
  return function(num) {
    arr.push(num);
  };
}

var arr = [1, 2, 3, 4];
var myArr = [];

arr.forEach(addToArr(myArr));

console.log(myArr);

In ES6 it's much easier to write with arrow functions.

const addToArr = arr => num => arr.push(num);
4castle
  • 32,613
  • 11
  • 69
  • 106
1

Alternatively, the second argument to forEach is used as the this value in the passed callback, so the following should work as well:

function addToArray (x) {
  this.push(x)
}

var array = [1, 2, 3, 4]
var otherArray = []
array.forEach(addToArray, otherArray)

console.log(otherArray)

If your intent was just to make a copy of the original array, though, I would suggest using Array#slice instead:

var array = [1, 2, 3, 4]
var otherArray = array.slice()

console.log(otherArray)
gyre
  • 16,369
  • 3
  • 37
  • 47