Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

find second smallest number in array javascript using for loop

const array = [32, 22, 53, 92, 20, 34, 23, 11, 17];
let smallestNum = array[0];
let secondSmallestNum = 0;
for (let i = 1; i < array.length; i++) {
  if (array[i] < smallestNum) {
    secondSmallestNum = smallestNum;
    smallestNum = array[i];
  } else if (array[i] !== smallestNum && array[i] < secondSmallestNum) {
    secondSmallestNum = array[i];
  }
}
console.log(smallestNum);
console.log(secondSmallestNum);
 
PREVIOUS NEXT
Tagged: #find #smallest #number #array #javascript #loop
ADD COMMENT
Topic
Name
6+2 =