1

I have 2 arrays in javascript.

            var A = ['c++', 'java', 'c', 'c#', ...];
            var B = [12, 3, 4, 25, ...];

Now from these 2 arrays i want to create another array like :

  [['c++',12], ['java',3], ['c',4], ['c#', 25] ...];

Both A and B arrays are variable length in my case so how can i do this?

gopi1410
  • 6,567
  • 9
  • 41
  • 75
user1476585
  • 81
  • 2
  • 4

4 Answers4

3

Underscore.js is good at that:

_.zip(*arrays)

Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes. If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion.

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
Otto Allmendinger
  • 27,448
  • 7
  • 68
  • 79
3

You can use this snippet if you don't to use any third party library:

var i = 0
  , n = A.length
  , C = [];

for (; i < n; i++) {
    C.push([A[i], B[i]]);
}
Florent
  • 12,310
  • 10
  • 49
  • 58
1
function Merge(A,B){
    var length = Math.min(A.length,B.length);
    var result = [];
    for(var i=0;i<length;i++){
     result.push([ A[i], B[i] ]) 
    }

    return result;
}
amd
  • 20,637
  • 6
  • 49
  • 67
0

I think that using a hashMap instead of 2 arrays could be a good solution for you.

In example, you could do something like the following:

var h = new Object(); // or just {}
h['c++'] = 12;
h['java'] = 3;
h['c'] = 4;

Take a look at:

http://www.mojavelinux.com/articles/javascript_hashes.html

jjordan
  • 183
  • 2
  • 6