Skip to content
Related Articles

Related Articles

How to create an array of elements, ungrouping the elements in an array produced by zip in JavaScript ?

Improve Article
Save Article
  • Last Updated : 14 Feb, 2022
Improve Article
Save Article

We can create an array of elements by ungrouping the elements in an array produced by zip by using different methods in JavaScript such as Math.max(), and array specific methods namely, Array.prototype.reduce() and Array.prototype.forEach(). This operation can also be termed as unzip.

Before looking at unzip, let us understand what zip does. Zip creates an array of elements, grouped based on their position in the original arrays. To achieve this, we can make use of JavaScript methods such as Math.max(), Array.from(), and


  • Math.max(): To get the longest array out of all argument arrays.
  • Then, create an array with that length as return value and use Array.from() with a mapping function to create an array of grouped elements.
  • To convert every array element into a new array.
  • Moreover, the spread operator (…) is used to represent a variable number of arrays that can be passed as arguments in the parameter field of the zip function.



const zip = (...arrays) => {
    const maxLength = Math.max( => arr.length));
    return Array.from({ length: maxLength })
    .map((_, i) => {
        return Array.from(
            {length: arrays.length }, 
            (_, j) => arrays[j][i]);
        [1, "GFG", 0.1],
        [2, "GeeksForGeeks", 0.2],
        [3, "Geeks", 0.3],
        [4, "For", 0.4],
        [5, "Geeks", 0.5]


Now let us look at how we can implement unzip:

  • Math.max(): Get the longest subarray in the array.
  • Make each array element into an array.
  • Array.prototype.reduce() and Array.prototype.forEach(): Map the grouped values to individual arrays.
  • Lastly, and the spread operator (…) are used to apply the f parameter in the unzip function to each individual group of elements.



const unzip = (arr, f) => arr.reduce(
    (a, myValue) => (myValue.forEach(
        (val, i) => a[i].push(val)), a),
        length: Math.max(
   => myArr.length)),
    }).map(myArr => [])
    .map(v => f(...v));
            [1, 3, 5],
            [2, 6, 10],
            [3, 9, 15],
        (...arguments) => arguments
            .reduce((acc, j) => acc + j, 0)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!