Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like 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(), 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 a 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: This example demonstrates the above-explained approach.

Javascript




<script>
    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]
        )
    );
</script>

Output:

Now let us look at how we can implement unzip:

Example: This example demonstrates the above-explained approach.

Javascript




<script>
    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)
        )
    );
</script>

Output:

[3,6,18]

My Personal Notes arrow_drop_up
Last Updated : 21 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials