Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ES6 - map multiple arrays

Tags:

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
like image 804
nha Avatar asked Oct 04 '15 18:10

nha


People also ask

Can you map two arrays in JavaScript?

Approach: For this, we can create two arrays, in which one array contains the array elements that are to be mapped, and the second array stores all the return values of the corresponding function. We can use the JavaScript Array push() method to push the return values of the function in the output array.

How do I return multiple values on a map?

let values = [1,2,3,4]; let newValues = values. map((v) => { return [v *v, v*v*v,v+1] ; }). reduce((a, c) => { return a.

Does map mutate array?

The map() method is a copying method. It does not alter this . However, the function provided as callbackFn can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn .

Does map return a new array?

The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .


1 Answers

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]
like image 82
Benjamin Gruenbaum Avatar answered Sep 17 '22 15:09

Benjamin Gruenbaum