Advertisement
PowerCell46

Smallest two numbers JS

Nov 28th, 2022
813
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function smallestTwoNums(array) {
  2.  
  3.     let smallestNumber = 10000000;
  4.  
  5.   for (let index = 0; index < Number(array.length); index++) {
  6.     let currentNum = array[index];
  7.     if (currentNum < smallestNumber) {
  8.       smallestNumber = currentNum; // in the first For cycle we get the smallest number
  9.     }
  10.   }
  11.  
  12.   let indexOfTheBiggestNum = array.indexOf(smallestNumber); // we learn the index of the smallest number
  13.   array.splice(indexOfTheBiggestNum, 1); // we remove the number from the array
  14.   let secondSmallestNum = 1000000;
  15.  
  16.   for (let index1 = 0; index1 < Number(array.length); index1++) {
  17.     let currentNum = array[index1];
  18.     if (currentNum < secondSmallestNum) {
  19.       secondSmallestNum = currentNum; // in the second For cycle we get the second smallest number
  20.     }
  21.   }
  22.  
  23.   let result = smallestNumber + " " + secondSmallestNum;
  24.   console.log(result);
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement