underscore.js: _.zip.apply example

2019-02-22 11:20发布

I would like to see an example of _.zip.apply using underscore.js.

In the underscore documentation is written:

If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion.

However, the documentation provides no example.

2条回答
男人必须洒脱
2楼-- · 2019-02-22 11:25

It's your standard use of apply:

_.zip.apply(null, [ ['foo','bar'], [0,1] ])

This would result in the following:

[['foo', 0], ['bar', 1]]
查看更多
迷人小祖宗
3楼-- · 2019-02-22 11:45

You can use also a 'non-external-library' method:

Create this function:

function transpose(arr) {
        return Object.keys(arr[0]).map(function (c) {
            return arr.map(function (r) {
                return r[c];
            });
        });
    }

and then:

var transposedArray = transpose(originalArray);

查看更多
登录 后发表回答