Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate through two lists at the same time in Underscore.js?

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.

like image 677
mrjoelkemp Avatar asked Apr 13 '12 00:04

mrjoelkemp


1 Answers

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/
like image 187
icyrock.com Avatar answered Nov 17 '22 01:11

icyrock.com