Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  4] [ 6]  / answers: 1 / hits: 36119  / 8 Years ago, thu, july 7, 2016, 12:00:00

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?


More From » arrays

 Answers
10

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);




[#61469] Wednesday, July 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emerald

Total Points: 547
Total Questions: 96
Total Answers: 122

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;