24

Is there a feature in JavaScript 6 that allows to map over multiple arrays ?

Something like a zipper :

 var myFn = function (a, b) { console.log(a, b);}
  var arr1 = ['a', 'b', 'c'];
  var arr2 = [1, 2, 3];

  arr1.map(myFn, arr2); // imaginary syntax.
  // prints :
  // a 1
  // b 2
  // c 3
nha
  • 17,623
  • 13
  • 87
  • 133
  • This seems to already answer the question: [http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function](http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) – HartleySan Oct 04 '15 at 19:13

4 Answers4

42

As the other answer points out, this is commonly known as a zip. It can be implemented as:

let zipped = arr1.map((x, i) => [x, arr2[i]]);

Or as a function, basically:

let zip = (a1, a2) => a1.map((x, i) => [x, a2[i]]); 

Which would let you do:

zip(["a","b","c"], [1,2,3]); // ["a", 1], ["b", 2], ["c", 3]
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
10

Unfortunately, no. What you are looking for is commonly called zip or zipWith. See lodash's implementation for a reference: https://lodash.com/docs#zipWith

lukewestby
  • 1,207
  • 8
  • 15
  • Aww. I know about lodash, but I can't use it right now. Do you have a source for that missing feature ? (Quite hard I know). – nha Oct 04 '15 at 19:02
  • No I am not asking for code? How do you know that it is missing ? Obviously "missing features" are not represented in the ES6 standard. So do you have a reference to point that it is missing ? – nha Oct 04 '15 at 19:05
  • 2
    Gotcha! Here's a link to the reference for `Array` on MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array It lists all of the methods available on `Array.prototype`, and you will find that the functionality you are looking for is not present. – lukewestby Oct 04 '15 at 19:06
  • Thanks, I will accept your answer as soon as I can. – nha Oct 04 '15 at 19:08
8

You could also use reduce to get the desired outcome:

var arr1 = ['a', 'b', 'c'];
var arr2 = [1, 2, 3];

arr1.reduce((acc, current, index) => {
   console.log(current, arr2[index])
   return [...acc, current, arr2[index]]
}, [])

// a 1
// b 2
// c 3
// returns ["a", 1, "b", 2, "c", 3]
Onaracs
  • 935
  • 3
  • 14
  • 22
  • 1
    This isn't what the user wanted, they wanted `["a", 1], ["b", 2], ["c", 3]`, not `["a", 1, "b", 2, "c", 3]` right? – Lifeweaver Aug 29 '22 at 16:14
1

Took reference from @Onaracs 's answer and edited it.

const arr1 = ['a', 'b', 'c']
const arr2 = [1, 2, 3]

const arr3 = arr1.reduce((acc, current, index) => {
  return [...acc, [current, arr2[index]]]
}, [])

console.log(arr3)