Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I zip two arrays in JavaScript?

People also ask

Can you map 2 arrays in JavaScript?

To map multiple arrays with JavaScript, we can use the map method. to define the zip function that calls a1. map to combine the entries from a1 and a2 with index i into one entry. Then we call zip with arr1 and arr2 to zip them into one array.

How do you zip an array?

Array#zip() : zip() is a Array class method which Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. Return: merges elements of self with corresponding elements from each argument.

How do you zip JavaScript?

js | zip() Function. The zip() function is used to combine the values of given array with the values of original collection at a given index. In JavaScript, the array is first converted to a collection and then the function is applied to the collection.

Does JavaScript have a Zip function?

tf. js users: if you need a zip function in python to work with tensorflow datasets in Javascript, you can use tf. data. zip() in Tensorflow.


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)

DEMO


Zip Arrays of same length:

Using Array.prototype.map()

const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]

Zip Arrays of different length:

Using Array.from()

const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);

console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]

Using Array.prototype.fill() and Array.prototype.map()

const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);

console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]