Third smallest number in an array using JavaScript

Problem

We are required to write a JavaScript function that takes in an array of numbers of length at least three.

Our function should simply return the third smallest number from the array.

Example

Following is the code ?

const arr = [6, 7, 3, 8, 2, 9, 4, 5];
const thirdSmallest = () => {
    const copy = arr.slice();
    for(let i = 0; i < 2; i++){
        const minIndex = copy.indexOf(Math.min(...copy));
        copy.splice(minIndex, 1);
    };
    return Math.min(...copy);
};
console.log(thirdSmallest(arr));

Output

4

Using Sort Method (Simpler Approach)

A more straightforward approach is to sort the array and pick the third element:

const arr = [6, 7, 3, 8, 2, 9, 4, 5];

function getThirdSmallest(numbers) {
    const sorted = numbers.slice().sort((a, b) => a - b);
    return sorted[2]; // Third element (index 2)
}

console.log(getThirdSmallest(arr));
4

Handling Duplicates

If the array contains duplicate values and you want the third unique smallest number:

const arr = [6, 7, 3, 8, 2, 9, 4, 5, 3, 2];

function getThirdUniqueSmallest(numbers) {
    const unique = [...new Set(numbers)];
    const sorted = unique.sort((a, b) => a - b);
    return sorted[2];
}

console.log(getThirdUniqueSmallest(arr));
4

Comparison of Methods

Method Time Complexity Handles Duplicates Readability
Remove Min Twice O(n²) No Medium
Sort Method O(n log n) No High
Sort with Set O(n log n) Yes High

Conclusion

The sort method provides the cleanest solution for finding the third smallest number. Use Set to remove duplicates if you need the third unique smallest value.

Updated on: 2026-03-15T23:19:00+05:30

639 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements