Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the smallest and largest value in an array with JavaScript

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?

like image 227
MadCatm2 Avatar asked Sep 05 '25 03:09

MadCatm2


2 Answers

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);
like image 91
Rick Hitchcock Avatar answered Sep 07 '25 23:09

Rick Hitchcock


Move your console.log statements outside of your for loop.

like image 33
Chester Millisock Jr Avatar answered Sep 08 '25 00:09

Chester Millisock Jr