javascript

Find the Third Smallest Number in an Array using Javascript

If you're looking for a quick and easy way to find the third smallest number in an array using Javascript, you've come to the right place. In this article, we'll show you how to do just that with a few simple lines of code.

Method #1: Sort the array in ascending order and get the 3rd element

The third smallest number in an array can be found by first sorting the array in ascending order. Then, the third smallest number will be the number at index 2 in the sorted array.

const numbers = [5, 9, 6, 3, 7, 5, 1, 2, 4];

numbers.sort(function (a, b) { return a - b });

console.log("Third smallest number: " + numbers[2]);

Output

Third smallest number: 3

Live code demo

This example shows how to sort an array using the sort() method. The sort method takes a callback function that defines how to sort the array.

In this example, the callback function compares two array elements and returns a value that is used to sort the array.

The sorted array is then logged to the console with the third smallest number being printed.


Method #2: Using Math.min() function

We can also use Math.min() function in Javascript to get the third smallest number in an array. We are removing the two smallest numbers from the copy of the array and then getting the 3rd lowest number.

Check the below code example to understand this.

const numbers = [5, 9, 6, 3, 7, 8, 4, 12, 11];

const num_copy = numbers.slice();
for (let i = 0; i < 2; i++) {
    const min_index = num_copy.indexOf(Math.min(...numbers));
    num_copy.splice(min_index, 1);
};
const result = Math.min(...num_copy);

console.log("Original Array is: ", numbers)
console.log("Third smallest number: " + result);

Output

Original Array is: [5,9,6,3,7,8,4,12,11]
Third smallest number: 4

Live code example

The above code finds the third smallest number in the array. It first copies the array using the slice method.

It then loops through the array twice, each time finding the index of the minimum number and splicing it out of the copied array.

Finally, it finds the minimum number of the remaining numbers in the array and prints it out.

Was this helpful?