1

I'm trying to find a javascript code that simultaneously enters data from two arrays and places them into one array. I thought this would work, but looking over it, it doesn't quite do the job.

var tempDeck = [];
var array1 = ["one", "two"];
var array2 = ["three", "four"];
for (i = 0; i < array1.length + array2.length; i++){
  if (i % 2 == 0){
    tempdeck.push(array1[i]);
  }else{
    tempdeck.push(array2[i]);
  }
}

I need it to output the result of

tempdeck[0] = "one";
tempdeck[1] = "three";
tempdeck[2] = "two";
tempdeck[3] = "four";

I'm trying to avoid manually placing them in, because the number or arrays is based on user input. :( Any suggestions?

2
  • instead of using for loop and push try to use array slice method developer.mozilla.org/en-US/docs/JavaScript/Reference/… Commented Apr 5, 2013 at 22:55
  • If the number of arrays is based on user input, then you probably don't actually have them stored in variables, right? But at the top of your question, you say it's two arrays... so which is it? Commented Apr 5, 2013 at 22:56

2 Answers 2

2

jsFiddle

You should just use the length of the larger array, and only add if a value exists at the index i.

var tempDeck = [];
var array1 = ["one", "two"];
var array2 = ["three", "four"];
var len = array1.length > array2.length ? array1.length : array2.length;
for (i = 0; i < len; i++){
  if( array1.length > i )tempDeck.push(array1[i]);
  if( array2.length > i )tempDeck.push(array2[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

http://underscorejs.org/#union

union_.union(*arrays) Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2, 3, 101, 10]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.