Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a single for loop iterate over multiple arrays?

In this case I'm using two parallel arrays (cost[] and scores[]) both of these with data on them that is parallel to each other.

This code is correct as am copying it from the book I'm using. What i don't get is how can this for loop work for the costs array. I get we are passing both arrays as parameters in the function but in the for loop there is only scores.length, so 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;
}
like image 830
Abraham Coronado Avatar asked Sep 28 '22 01:09

Abraham Coronado


1 Answers

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

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

If they both are truly parallel than both arrays are going to be 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]);
}

Output:

1 4
2 5
3 6

Using b's length

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

Output:

1 4
2 5
3 6
like image 116
Patrick Evans Avatar answered Oct 12 '22 23:10

Patrick Evans