BeeNag BeeNag - 2 years ago 103
Javascript Question

manipulating arrays in javascript

I have two arrays like so

var arr1 = ["1", "2", "3", "4"];
var arr2 = [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"], ["m", "n", "o", "p"], ["q", "r", "s", "t"]];

What I would like to do is merge the two arrays to form a final output that looks like this

var newArr = [{1: "a", 2: "b", 3: "c", 4: "d"}, {1: "e", 2: "f", 3: "g", 4: "h"}, {1: "i", 2: "j", 3: "k", 4: "l"}, {1: "m", 2: "n", 3: "o", 4: "p"}, {1: "q", 2: "r", 3: "s", 4: "t"}];

So effectively take each array out of the second array and then merge it with the first array to form an object.

I was just wandering what the most efficient way to do this in javascript would be?

Any help would be much appreciated

Thanks for your time

Answer Source

Assuming the input always matches, I'd start with arr2: => 

However, at this point what you want is to zip values from x and the corresponding values from y together, so let's introduce a helper first (I'm actually gonna call it zipKeyVal1 because it maps values from first param to keys, and the second to values).

function zipKeyVal(a,b) {
    var result = {};
    for (var i = 0; i < a.length; i++) {
        result[a[i]] = b[i];
    return result;

With that, our solution becomes:

var newArr = => zipKeyVal(arr1, x));

1Oh, apparently underscore.js calls that _.object, and lodash zipObject.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download