10

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.

user3335966
  • 2,673
  • 4
  • 30
  • 33
mrjoelkemp
  • 431
  • 1
  • 6
  • 12

1 Answers1

15

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:

icyrock.com
  • 27,952
  • 4
  • 66
  • 85
  • @icyrock.com When I replace the values in the arrays `a` and `b` with **Strings** Underscore's `_.zip` function stores the **length of the array** instead of the value. Can you confirm this? How would you implement the same scenario but with Strings instead of Integers? – JJD May 07 '13 at 16:41
  • I started a question on `String` arrays [here](http://stackoverflow.com/questions/16426293/javascript-how-to-merge-the-string-values-of-two-arrays). There seems to be buggy behavior in the **Chromium** browser. – JJD May 07 '13 at 19:35
  • Is it better or more efficient than using nested 'for' loops? Why would you prefer this way or the other? – Vali D Aug 25 '16 at 06:54
  • `ReferenceError: _ is not defined`; looks like this is not actually part of the standard library. Also, your link doesnt work. – user5359531 Jun 09 '21 at 18:11
  • @user5359531 `_` is part of underscore.js. Check the docs out on how to install / use or the jsfiddle link I provided for a working example. Updated the docs link - thanks! – icyrock.com Jun 09 '21 at 18:20
  • Thanks but I cannot install 3rd party packages I can only use native JS – user5359531 Jun 09 '21 at 18:21
  • 1
    @user5359531 This is tagged underscore.js, so it doesn't apply to your situation. You do have options, e.g: 1) copy the code for `zip` from underscore.js 2) search SO for other similar questions (here's one: https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) – icyrock.com Jun 09 '21 at 18:26