Find Largest /Smallest /Second Largest /Second Smallest Elements of an Array JavaScript

15-06-2022

Here we discuss how to find the largest, smallest, second largest, second smallest elements of an array in JavaScript.

Find Largest /Smallest Elements of an Array JavaScript



var numbers = [12, 5, 6, 8, 7, 4, 26, 21, 23];
largest         = numbers[0];
smallest        = numbers[0];
second_largest  = numbers[0];
second_smallest = numbers[0];

for(i=0; i<numbers.length; i++){ //find largest 
   if(numbers[i] > largest){
        largest = numbers[i];
    }

    //find smallest
    if(numbers[i] < smallest){
        smallest = numbers[i];
    }
}

for(i=0; i<numbers.length; i++){ //find second largest 
    if(numbers[i] > second_largest && numbers[i] < largest){
        second_largest = numbers[i];
    }

    //find second smallest
    if(numbers[i] < second_smallest && numbers[i] > smallest){
        second_smallest = numbers[i];
    }
}

console.log('Largest : ' + largest);
console.log('Second Largest : ' + second_largest);
console.log('Smallest : ' + smallest);
console.log('Second Smallest : ' + second_smallest);

 

Output