Do sorting an Array in ascending order and get 2nd number is one way. Other ways are to get the second smallest number from array JavaScript is traversing the array twice or traversing the array and store it as the smallest element.
get second smallest number in array JavaScript Example
HTML example code:
Sorting the array
This will first sort your array and get first index value.
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [ 6, 3, 5, 2, 9 ];
arr.sort((a,b) => a-b);
const secondMin = arr[1];
console.log(secondMin);
</script>
</body>
</html>
Traversing the array
- If the current element is smaller than the smallest, then update the smallest.
- Else if the current element is greater than smallest and less than secondsmallest then update secondsmallest.
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [ 6, 3, 5, 2, 9 ];
var smallest = arr[0];
var secondSmallest = arr[1];
for(var i = 0; i < arr.length; i++) {
if(arr[i] < smallest) {
smallest = arr[i];
}
if(arr[i] > smallest && arr[i] < secondSmallest ) {
secondSmallest = arr[i];
}
}
console.log(secondSmallest);
</script>
</body>
</html>
Output: It will same for both example because the array values are same.
Do comment if you have any doubts and suggestions on this JS Array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
Traversing the array is failing for this use case
var arr = [19,30,190,20,2,56,60];