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.map(), 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 Array.prototype.map()

Approach:

  • 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.
  • Array.prototype.map(): 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.

Example:

Javascript




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


Output:

Now let us look at how we can implement unzip:

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

Example:

Javascript




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


Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!