3

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 sleeping! :)

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

0

4 Answers 4

4
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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

Assuming both are equal in length:

var c = [];

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

Comments

1

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

Comments

0

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.