views:

71

answers:

6

I have:

var array1 = [];
var array2 = [];

array1 contains 1,2

array2 contains 3,4

And I want to do this:

for(var a in array1){
    for(var b in array2){
         doSomething(array1[a],array2[b]);
    }
}

But the problem is that function doSomething() runs twice for each array because of the two for's.

How should run it just once but with all of the arrays?

EDIT

The numbers are not in ascending order! In my real project they are ID's what can be any number in any order.

+3  A: 

You shouldn't use for..in for looping through arrays. Use an index variable:

for (var i = 0, len = array1.length; i < len; i++) {
    doSomething(array1[i], array2[i]);
}

This of course assumes they're the same length.

Matti Virkkunen
Thanks very much for your answer! Because you were the first I will accept your answer in 4 minutes after the system let me do it!
CIRK
Note that the advice “You shouldn't use `for..in` for looping through arrays” is good for *all* cases, not just when you have two arrays. `for...in` on an `Array` is almost always a mistake, it iterates the object's property names (not just integer indexes) in any arbitrary order.
bobince
+1  A: 

I think this is what you're after:

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

This loops through both arrays, using the first for the length, and taking the element at the same index in both for each doSomething() call.

Nick Craver
+1  A: 

If you are sure that both arrays have the exact same length, you can do the following:

for (var i = 0; i < array1.length; i++) {
    doSomething(array1[i], array2[i]);
}
elusive
+1  A: 

It looks like you want to concatenate two arrays together. Use the concat() function:

var jointArray = array1.concat(array2);
for(var i=0; i < jointArray.length; i++) {
 doSomething(jointArray[i]);
}

See:

http://www.w3schools.com/jsref/jsref_concat_array.asp

RMorrisey
+1  A: 

This if array arent same length

for (var i = 0, i < (array1.length <= array2.length ? array1.length : array2.length); i++) {
    doSomething(array1[i], array2[i]);
}
Mark Baijens
I would use `Math.min` and store the minimum length on a variable to avoid that comparison on each iteration, e.g.: `for (var i = 0, len = Math.min(a1.length, a2.length); i < len; i++) { }`
CMS
+1  A: 

DoSomething will run 4 times. If you want it to just run through the values both list together, remove the second for loop and replace b in DoSomething with a.

Alexander Rafferty