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?

8
  • It is a good idea to put your code that you have tried so far. Commented Jul 11, 2012 at 10:11
  • 1
    What have you tried? Commented Jul 11, 2012 at 10:11
  • possible duplicate of How to flatten array in jQuery? Commented Jul 11, 2012 at 10:11
  • 1
    Are those your actual arrays? You might want to add commas between the elements! Commented Jul 11, 2012 at 10:12
  • @LinusKleen flatten != zip Commented Jul 11, 2012 at 10:12

4 Answers 4

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]]
Sign up to request clarification or add additional context in comments.

Comments

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]]);
}

Comments

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;
}

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.