RyBrennan
RyBrennan

Reputation: 13

How does this while loop condition work?

This function returns a single number after every-other number has been removed. For instance, on the first run, from left to right- 3, 7, and 9 are removed. Then the loop goes on the next iteration from right- to left until finally, just 8 is left.

I don’t understand why only one element (number) is getting pushed to the array. How is this while loop working? Where exactly is the 'filtering taking place? Also, the .reverse function is throwing me off. How does this code know how to go left-to-right, then right-to-left multiple times?

So yeah, any help would be greatly appreciated;-) Thank you

function everyOtherfilter(values){
while (values.length > 1){

    new_values = [];
    for (var i=1; i < values.length; i = i+2){
        new_values.push(values[i]);

    }
    values = new_values.reverse();
}

return values[0]

}
(everyOtherFilter([3, 5, 7, 8, 9, 2])) = 8

Upvotes: 1

Views: 73

Answers (2)

John Michael Villegas
John Michael Villegas

Reputation: 336

do{/*statements*/}while(/*condition*/)

the do while statement is do the statement first then check your condition if true it will do the statements again if false terminate the loop.

while(/*conditions*/){/*statements*/}

the while loop check first the condition if true do the statements. after doing the statement it will check the condition again if false terminate the loop

   for(/*initialize some index*/;/*condition*/;/*index changes*/){/*statements*/}

the for loop initialize index then check the condition if true do the statements then increment the index check condition if false terminate loop

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

I don't know what actual purpose this function serves, but we can easily run your function with the sample data you provided:

3 5 7 8 9 2
  ^   ^   ^    (i = 1, 3, 5)

After pushing the selected values (highlighted above) into new_values we are left with the following array:

5 8 2

Now values gets assigned the reverse of this array:

2 8 5
  ^            (i = 1)

During the next iteration of the outer while loop, only a single element gets pushed onto new_values, which is the value at index 1, the number 8, which also happens to be the center of the array. So at the end of the second iteration, the values array just has one element:

8

The while loop does not iterate again, because the length is just 1 at this point.

Upvotes: 2

Related Questions