Is it possible to iterate through two lists at the

2019-04-05 08:45发布

问题:

I basically want to express the following behavior using _.each() or _.map() in Underscore.js.

a = [1, 2, 3]
b = [3, 2, 1]

# Result list
c = [0, 0, 0]

for i in [0 .. a.length - 1]
   c[i] = a[i] + b[i]

This is definitely possible in Matlab (my primary language) as such:

c = arrayfun(@(x,y) x+y, a, b)

Intuitively, it feels like the syntax in Underscore should be:

c = _.map(a, b, function(x, y){ return x + y;})

However, that argument list isn't acceptable; the second parameter is supposed to be a callable function.

The optional "context" argument won't help me in this situation.

回答1:

Use zip (also from underscore.js) for that. Something like this:

var a = [1, 2, 3];
var b = [4, 5, 6];
var zipped = _.zip(a, b);
// This gives you:
// zipped = [[1, 4], [2, 5], [3, 6]]

var c = _.map(zipped, function(pair) {
  var first = pair[0];
  var second = pair[1];
  return first + second;
});

// This gives you:
// c = [5, 7, 9]

Working example:

  • http://jsfiddle.net/beRAD/