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?
The easiest way to do this would be to sort the array, then return the first two and last two elements.
Using slice()
prevents the array itself from being sorted:
var numbers = [2, 4, 9, 2, 0, 16, 24];
var sorted = numbers.slice().sort(function(a, b) {
return a - b;
});
var smallest = sorted[0],
secondSmallest = sorted[1],
secondLargest = sorted[sorted.length - 2],
largest = sorted[sorted.length - 1];
console.log('Smallest: ' + smallest);
console.log('Second Smallest: ' + secondSmallest);
console.log('Second Largest: ' + secondLargest);
console.log('Largest: ' + largest);
Move your console.log statements outside of your for loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With