I have 2 arrays:
var a = [1, 2, 3]
var b = [a, b, c]
What I want to get as a result is:
[[1, a], [2, b], [3, c]]
It seems simple but I just can't figure out.
I want the result to be one array with each of the elements from the two arrays zipped together.
Use the map
method:
var a = [1, 2, 3]
var b = ['a', 'b', 'c']
var c = a.map(function(e, i) {
return [e, b[i]];
});
console.log(c)
Using Array.prototype.map()
const a = [1, 2, 3],
b = ['a', 'b', 'c'];
const zip = (arr1, arr2) => arr1.map((k, i) => [k, arr2[i]]);
console.log(zip(a, b)) // [[1, "a"], [2, "b"], [3, "c"]]
Using for
loop
var a = [1, 2, 3],
b = ['a', 'b', 'c'];
var zip = [];
for (var i = 0; i < a.length; i++){
zip.push([a[i], b[i]]);
}
console.log(zip); // [[1, "a"], [2, "b"], [3, "c"]]
©2020 All rights reserved.