user7364699
user7364699

Reputation:

Need some clarification for the code provided

I am trying to understand this JavaScript code

var arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];

var main = [];
var long;

for(var i=0; i<arr.length; i++){
    long = arr[i][0]; //setting the long var first element of array
    for(var j=0; j<arr.length; j++){
        //comparing first elelment of array (long) with arr[i][j] ie dynamic
        if(arr[i][j] > long) {
             long= arr[i][j];
        }
    }
     main.push(long);
}
return main;

I have understood most of it except the part long = arr[i][0];.

I understand that in the if statement we are comparing arr[i][j] with arr[i][0] but the problem is I do not understand how the computer is comparing it.

I have checked arr[i][0] and it gives first element of all the arrays present in arr array.

I am guessing it is comparing each value with the arr[i][j]? but I am not sure.

Can someone please clarify it?

Sorry if this is a silly question I am just a beginner and thank you in advance.

Upvotes: -1

Views: 64

Answers (2)

Siop
Siop

Reputation: 1

This code snippet is searching this 2D array for the largest values of each nested array. On the initial assignment operation long = arr[i][0] the author is assigning the first element of each nested array to long on each iteration of the outer loop. On each iteration of the nested(inner) loop we are stepping through a nested array, comparing each element with what long points to(first item of this nested array) if that value is larger than long(predicate is satisfied) than push it to main, else continue to step through this array searching for the largest value; if long is the largest, than push it to main. This is a algorithm to find the largest value in a 2D dimensional array.

on each iteration of the outer loop, long is being rebound(referencing a new value, that is of a nested array).

The output would be:

main = [5, 27, 39, 1001]; 

Upvotes: -1

DFord
DFord

Reputation: 2358

The line long = arr[i][0]; is assigning the value is arr[i][0] to var long. That is setting the first value of each array to the longest value. Then it will iterate through the rest of the values of the array and if it finds a value larger than long, it will assign that value to long with this block of code

if(arr[i][j] > long) {
     long= arr[i][j];
}

Then, finish processing the rest of the array.

Finally largest value of that array, long will get pushed to main.

Upvotes: 0

Related Questions