I am trying to write an algorithm that finds and smallest and largest value in an array, and the second largest and second smallest.
I tried with the following:
numbers = [2, 4, 9, 2, 0, 16, 24]
var largest = numbers[0];
var smallest = numbers[0];
for (var i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
} else if (numbers[i] < smallest) {
smallest = numbers[i];
}
console.log(largest);
console.log(smallest);
}
This does not seem to work and just prints out the array...what am I doing wrong?
console.log
statements outside the loop.numbers
array.1
andn-2
(assumingn-1
is the last element and0
is the first).