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