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
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.
let values = [1,2,3,4]; let newValues = values. map((v) => { return [v *v, v*v*v,v+1] ; }). reduce((a, c) => { return a.
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 .
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 .
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With