Javascript equivalent of Python's zip function

前端 未结 18 1663
天命终不由人
天命终不由人 2020-11-21 07:40

Is there a javascript equivalent of Python\'s zip function? That is, given multiple arrays of equal lengths create an array of pairs.

For instance, if I have three

18条回答
  •  囚心锁ツ
    2020-11-21 07:52

    I took a run at this in pure JS wondering how the plugins posted above got the job done. Here's my result. I'll preface this by saying that I have no idea how stable this will be in IE and the like. It's just a quick mockup.

    init();
    
    function init() {
        var one = [0, 1, 2, 3];
        var two = [4, 5, 6, 7];
        var three = [8, 9, 10, 11, 12];
        var four = zip(one, two, one);
        //returns array
        //four = zip(one, two, three);
        //returns false since three.length !== two.length
        console.log(four);
    }
    
    function zip() {
        for (var i = 0; i < arguments.length; i++) {
            if (!arguments[i].length || !arguments.toString()) {
                return false;
            }
            if (i >= 1) {
                if (arguments[i].length !== arguments[i - 1].length) {
                    return false;
                }
            }
        }
        var zipped = [];
        for (var j = 0; j < arguments[0].length; j++) {
            var toBeZipped = [];
            for (var k = 0; k < arguments.length; k++) {
                toBeZipped.push(arguments[k][j]);
            }
            zipped.push(toBeZipped);
        }
        return zipped;
    }

    It's not bulletproof, but it's still interesting.

提交回复
热议问题