0

I'm trying to use the underscore.js each function to push each element of an array onto an existing array, in-place.

To do this, I assumed I could use the push array method, rather than the usual anonymous function passed to each, provided that I passed a context object as the 3rd argument to each:

> var a = [1,2,3]
> var b = []
> _.each(a, b.push, b)

I'd expect b to now be [1,2,3], but it is actually:

Array [ 1, 0, Array[3], 2, 1, Array[3], 3, 2, Array[3] ]

What is going on?

DNA
  • 42,007
  • 12
  • 107
  • 146

1 Answers1

0

_.each doesn't work in the same way as foreach in many other functional programming languages or libraries. As described in the documentation,

Each invocation of iteratee is called with three arguments: (element, index, list)

If you instead use console methods, you can see this:

> _.each(a, console.log, console)

  1 0 Array [ 1, 2, 3 ]
  2 1 Array [ 1, 2, 3 ]
  3 2 Array [ 1, 2, 3 ]

so push ends up accepting those nine values, rather than the three one might hope for. One can just use an anonymous function:

_.each(a, function(x) { b.push(x) })

and b is then [1,2,3] as expected.

Or, in this particular case, use one of the other ways to extend an array in JavaScript.

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146