h_houtarou
h_houtarou

Reputation: 57

sub array of longest positive integer. Compiler doesn't make sense

I'm checking every number of an array, where if the number is positive and greater than 0, a variable call 'length' will be incremented. and if not then 'length' variable will be set to 0. but for the array element 2 and 7 it's always entering else mode and setting my 'length' variable to 0. but clearly 2 and 7 is greater than 0.

I've already tried 3 different compiler and also chrome developer console. I can't understand what's wrong.

function longestSequence(arr) {
    let longest = 0;
    let length = 0;
    for(let i of arr) {
        if(arr[i] > 0) {
            length = length + 1;
            console.log("for "+i+" length "+length);   
        }
        else {
            length = 0;
            console.log("for "+i+" length "+length);
        }
        if(length > longest) {
            longest = length;
        }
    }
    return longest;
}
const ara = [3, 2, -4, 7, 1, 5, 6];
console.log(longestSequence(ara));

Output:

'for 3 length 1'
'for 2 length 0'
'for -4 length 0'
'for 7 length 0'
'for 1 length 1'
'for 5 length 2'
'for 6 length 3'
3

but clearly 'for 2 length 0' should be 'for 2 length 2' and 'for 7 length 0' should be 'for 7 length 1' and the value of that function should be 4. can anyone tell me what's wrong? thanks in advance

Upvotes: 4

Views: 45

Answers (1)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

Here i is not the index but the array element itself, for..of loop iterates through each element of the iterable:

function longestSequence(arr) {
    let longest = 0;
    let length = 0;
    for(let i of arr) {
        if(i > 0) {
            length = length + 1;
            console.log("for "+i+" length "+length);   
        }
        else {
            length = 0;
            console.log("for "+i+" length "+length);
        }
        if(length > longest) {
            longest = length;
        }
    }
    return longest;
}
const ara = [3, 2, -4, 7, 1, 5, 6];
console.log(longestSequence(ara));

From the MDN docs:

for (variable of iterable) { statement }

variable
On each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var.

Upvotes: 4

Related Questions