Reputation: 81
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?
Upvotes: 1
Views: 178
Reputation: 183
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
Upvotes: 0
Reputation: 21442
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;
}
Upvotes: 1
Reputation: 12420
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]]);
}
Upvotes: 3
Reputation: 28268
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]]
Upvotes: 3