8

This is based on my last question.

I have these arrays:

var array1 = new Array ("Pepsi", "Coke", "Juice", "Water"); var array2 = new Array ("35", "17", "21", "99"); 

And I want to combine them to form a multidimensional array like this:

[ ["Pepsi","35"] ["Coke", "17"] ["Juice","21"] ["Water","99"] ] 

I tried this script:

Values=[]; for (i = 0; i < array1.length; i++) { Values[i] = Array(array1[i], array2[i]); } 

But it gave a result like this (correct values, incorrect names):

[ ["a","35"] ["c","17"] ["E","21"] ["I","99"] ] 
3
  • 4
    What you have works for me Commented May 16, 2012 at 17:35
  • 2
    Your code is correct, at least on Firefox and Opera... Commented May 16, 2012 at 17:36
  • Where would the capital E and I come from, or are those typos? Commented May 16, 2012 at 17:41

2 Answers 2

18
var array1 = ["Pepsi", "Coke", "Juice", "Water"], array2 = ["35", "17", "21", "99"], result = [], i = -1; while ( array1[++i] ) { result.push( [ array1[i], array2[i] ] ); } 

As written, this solution assumes you will only ever be using strings. As @ajax333221 has pointed out in the comments below, this would cause problems if you were to involve boolean or int values into this solution. As such, I'd like to propose an improvement that will accomplish your goals, while not tripping over difficult values and types:

var array1 = [false, 0, "Juice", -1], array2 = ["35", "17", "21", "99"], result = []; for ( var i = 0; i < array1.length; i++ ) { result.push( [ array1[i], array2[i] ] ); } 
Sign up to request clarification or add additional context in comments.

4 Comments

you assumed he will always work with strings. If he works with other things like numbers 0 or booleans false, there will be problems
@ajax333221 Yes, I'm assuming the question represents the problem.
@JonathanSampson And I will now assume you don't like to write maintainable and flexible code
@ajax333221 I appreciate your advice, and I've added a for loop to side-step any issues with types and values of the falsey nature.
13

You can use .map() on Arrays.

var Values = array1.map(function(v,i) { return [v, array2[i]]; }); 

See the MDN shim for older browsers.

live demo: http://jsfiddle.net/D9rjf/


If you're going to do this operation quite a bit, you could make a reusable function.

In this example, I extended Array.prototype, but that's not necessary if you don't like that.

Array.prototype.combine = function(arr) { return this.map(function(v,i) { return [v, arr[i]]; }); }; 

var Values = array1.combine(array2); 

live demo: http://jsfiddle.net/D9rjf/1/

1 Comment

not enough answers on SO like this using non-destructive methods to create arrays

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.