2

In this question, one of the answers code is:

var arrays = [[1,2,3,4,5,6], [1,1,1,1,1,1], [2,2,2,2,2,2]];

_.map(_.zip.apply(_, arrays), function(pieces) {
     return _.reduce(pieces, function(m, p) {return m+p;}, 0);
});

in apply(_, arrays) I don't understand to what _ is related.

Community
  • 1
  • 1
Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
  • 1
    _ is an object defined in underscore.js (http://underscorejs.org/) ... my best guess, it's like $ for jQuery (except $ is used in many more) ... and must be a function object – Marco Gabriel Godoy Lema Oct 16 '13 at 13:00

2 Answers2

5

The apply call is equivalent to

_.zip([1,2,3,4,5,6], [1,1,1,1,1,1], [2,2,2,2,2,2])

The first argument to apply makes sure that zip is called with the right context (this value) which usually is _, Underscore's namespace-constructor-function-object. Actually it's not used in the zip function, so we could've omitted it and passed null or undefined instead.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • why don't you use `_.partial(_.zip,arrays)` ? – Stephane Rolland Oct 16 '13 at 13:15
  • 1
    `_.partial` is for currying a function, which is not suitable here. It returns a function, not an array – Herrington Darkholme Oct 16 '13 at 13:19
  • @StephaneRolland: What for, instead of the `apply`? Because that doesn't invoke `zip`, calls it with the wrong arguments and doesn't return an array but a function. Check [what `_.partial` does](http://underscorejs.org/#partial). – Bergi Oct 16 '13 at 13:19
1

There is no much meaning in that _.

See the official page demo http://underscorejs.org/#zip

The main point here is apply, which accepts the second argument arrays as arguments.

So _.zip(arr1, arr2, arr3) is actually the same as _.zip.apply( null,[arr1,arr2, arr3])

The first argument, which acts as this keyword, can be anything. The choice of _ is probably a meme and underscores the usage of _. Just follow it :) enter image description here

Herrington Darkholme
  • 5,979
  • 1
  • 27
  • 43