Alex
Alex

Reputation: 181

How to merge two arrays as key/val

How can you merge two arrays into key/value pairs please?

From this...

array1 = ['test1', 'test2'];
array2 = ['1', '2'];

To this...

array3 = ['test1':'1', 'test2':'2'];

Upvotes: 5

Views: 4261

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

See http://phpjs.org/functions/array_combine:307

EDIT: Looking at your question again, you might be after something more like this:

function mergeArrays(arr1, arr2) {
    var l = Math.min(arr1.length,arr2.length),
            ret = [],
            i;

    for( i=0; i<l; i++) {
       ret.push(arr1[i]+":"+arr2[i]);
    }

    return ret;
}

Upvotes: 4

Erik Hinton
Erik Hinton

Reputation: 1946

If you are using underscore.js http://documentcloud.github.com/underscore/#zip you can simply do:

var zipped = _.zip(array1,array2);
_(zipped).map(function(v){ return v[0] + ":" + v[1] });

Upvotes: 5

Related Questions