How to use the zip function from underscore

Find comprehensive JavaScript underscore.zip code examples handpicked from public code repositorys.

underscore.zip creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.

5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
// an index go together.
_.zip = function() {
  return _.unzip(arguments);
};

// Complement of _.zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices
_.unzip = function(array) {
  var length = array && _.max(array, getLength).length || 0;
  var result = Array(length);
fork icon0
star icon2
watch icon0

How does underscore.zip work?

Underscore's zip function creates an array of grouped elements, where the nth element of each input array are combined together to form a new array of n elements. For example, if you pass two arrays ['a', 'b', 'c'] and [1, 2, 3] to _.zip(), it will return [['a', 1], ['b', 2], ['c', 3]]. If the input arrays are of different lengths, the resulting array will have a length equal to the shortest input array.

Ai Example

1
2
3
4
5
6
7
const names = ["Alice", "Bob", "Charlie"];
const ages = [24, 35, 18];
const cities = ["New York", "San Francisco", "Chicago"];

const zipped = _.zip(names, ages, cities);
console.log(zipped);
// Output: [['Alice', 24, 'New York'], ['Bob', 35, 'San Francisco'], ['Charlie', 18, 'Chicago']]