How to loop one loop for a loop across multiple arrays?

In this case, I use two parallel arrays ( cost[] and scores[] ), both of which have data on them that are parallel to each other.

This code is correct as I copy it from the book I use. What I am not getting is how it can work for a loop for an array of costs. I get that we pass both arrays as parameters in the function, but in the for loop there is only scores.length , so there shouldn't be another loop for cost.lenght ?

 function getMostCostEffectiveSolution(scores, costs, highScore) var cost = 100; var index; for (var i = 0; i < scores.length; i++) { if (scores[i] == highScore) { if(cost > cost[i]) { index = i; cost = cost[i]; } } } return index; } 
+5
source share
1 answer

http://en.wikipedia.org/wiki/Parallel_array

In computing, a group of parallel arrays is a data structure for records representing arrays. It stores a separate homogeneous array for each record field , each of which has the same number of elements

If both of them are really parallel, then both arrays will have the same length.

So scores.length == costs.length . You only need to use one for the loop condition and use the same index variable to access both arrays.

Example

 var a = [1,2,3]; var b = [4,5,6]; for(var i=0; i<a.length; i++){ console.log(a[i] +" "+ b[i]); } 

Conclusion:

 1 4 2 5 3 6 

Using length b

 for(var i=0; i<b.length; i++){ console.log(a[i] +" "+ b[i]); } 

Conclusion:

 1 4 2 5 3 6 
+4
source

All Articles