Open In App

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

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:

Example: This example demonstrates the above-explained approach.






<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.




<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]

Article Tags :