How to use iteration In Javascript
In this approach, we iterate through the array to find the smallest and second smallest elements simultaneously. We maintain two variables to store the current smallest and second smallest elements while scanning the array.
Example: The below code Find the Second Smallest Element in an Array using linear scan in JavaScript.
function secondSmallestElement(arr) {
let smallest = Infinity;
let secondSmallest = Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
secondSmallest = smallest;
smallest = arr[i];
} else if (arr[i] < secondSmallest && arr[i] !== smallest) {
secondSmallest = arr[i];
}
}
return secondSmallest;
}
const numbers = [5, 2, 8, 3, 1, 7];
console.log("Second smallest element:", secondSmallestElement(numbers));
Output
Second smallest element: 2
Find Second Smallest Element in an Array in JavaScript
JavaScript allows us to compute the Second Smallest Element within a given array. The task involves iterating through the array, identifying the smallest and second smallest element in the array.
There are several approaches to finding the second smallest element in an array using Javascript which are as follows:
Table of Content
- Using Sort method()
- Using iteration
- Using Math.min and filter()