Open In App

Find Second Smallest Element in an Array in JavaScript

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using Sort method()

In this approach, we sort the array in ascending order using the sort method and return the second element which is the second smallest element in the array.

Example: The below code Finds the Second Smallest Element in an Array using sorting in JavaScript.

Javascript
function secondSmallestElement(arr) {
    arr.sort((a, b) => a - b);
    return arr[1];
}

const numbers = [5, 2, 8, 3, 1, 7];
console.log("Second smallest element:", secondSmallestElement(numbers));

Output
Second smallest element: 2

Using iteration

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.

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

Using Math.min and filter()

Find the minimum value in the array using Math.min and exclude the smallest element using filter method.

Example: This JavaScript code uses filtering to exclude the smallest element and then finds the minimum of the remaining array, effectively determining the second smallest element.

Javascript
function secondSmallest(arr) {
    const smallest = Math.min(...arr);
    const filteredArray = arr
        .filter(num => num !== smallest);
    return Math.min(...filteredArray);
}

console.log(secondSmallest([1, 12, 13, 2,]))

Output
2

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads