开发者

Combining Arrays in Javascript

Maybe it's too late in Germany (1:04AM) or maybe I'm missing something...

How can I combine these two arrays:

a = [1, 2, 3] and b = [a, b, c] so that i get: [[1, a], [2, b], [3, c]]

Thank and ... spend more time s开发者_运维百科leeping! :)

Edit:

I see this function is called "zip". +1 Knowledge

And there is no built-in function in JavaScript for this. +1 Knowledge

And I should have said that the arrays are equal in length. -1 Knowledge


Array.prototype.zip = function(other) {
    if (!Array.prototype.isPrototypeOf(other)) {
         // Are you lenient?
         // return [];
         // or strict?
         throw new TypeError('Expecting an array dummy!');
    }
    if (this.length !== other.length) {
         // Do you care if some undefined values
         // make it into the result?
         throw new Error('Must be the same length!');
    }
    var r = [];
    for (var i = 0, length = this.length; i < length; i++) {
        r.push([this[i], other[i]]);    
    }
    return r;
}


Assuming both are equal in length:

var c = [];

for (var i = 0; i < a.length; i++) {
    c.push([a[i], b[i]]);
}


You might want to check underscore.js which contains lots of needed utility function. In your case function *_.zip()*

_.zip([1, 2, 3], [a, b, c]);

results as:

[[1, a], [2, b], [3, c]]


In ES6, we can use .map() method to zip both arrays (assuming both arrays are equal in length):

let a = [1, 2, 3],
    b = ['a', 'b', 'c'];
    
let zip = (a1, a2) => a1.map((v, i) => [v, a2[i]]);

console.log(zip(a, b));
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜