Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combaining two array into single multi dimensional array in javascript

status_name=Array("a","b","c","b","e","f");
status_id=Array( 1, 2, 3, 4, 5, 6);

How to combine these two arrays and to built multi dimensional array Expected Multidimensional array be like this

[["a", 1],["b", 2],["c", 3],["d", 4],["e", 5],["f", 6]]

Help me how to use above two array values and built my expected multidimensional array

like image 599
Mohan Ram Avatar asked Apr 16 '26 05:04

Mohan Ram


2 Answers

Since you're including jQuery, you can use jQuery.map in a similar fashion to Linus' answer:

var result      = [],
    status_name = ["a","b","c","b","e","f"],
    status_id   = [1, 2, 3, 4, 5, 6];

result = $.map(status_name, function (el, idx) {
    return [[el, status_id[idx]]];
}); 

Looking at your variable names, I'd guess that your coming from a language (like PHP). If that's the case, make sure you remember to declare local variables with the var keyword, otherwise you'll be polluting the global scope and you'll run into some hideous bugs in IE.

like image 177
Andy E Avatar answered Apr 18 '26 19:04

Andy E


JavaScript has no buitin method for this, but you can easily write it yourself:

function zip(arrayA, arrayB) {
    var length = Math.min(arrayA.length, arrayB.length);
    var result = [];
    for (var n = 0; n < length; n++) {
        result.push([arrayA[n], arrayB[n]]);
    }
    return result;
}

The name zip is chosen because a function that does something like this is often called zip in other languages.

like image 44
Christoph Henkelmann Avatar answered Apr 18 '26 20:04

Christoph Henkelmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!