Bigbohne
Bigbohne

Reputation: 1356

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

Upvotes: 3

Views: 723

Answers (4)

Mohammad Usman
Mohammad Usman

Reputation: 39392

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

Upvotes: 0

Mika Tuupola
Mika Tuupola

Reputation: 20407

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

Upvotes: 1

ChaosPandion
ChaosPandion

Reputation: 78292

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

Upvotes: 4

BoltClock
BoltClock

Reputation: 724502

Assuming both are equal in length:

var c = [];

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

Upvotes: 3

Related Questions