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 −

 Live Demo

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

Updated on: 17-Apr-2021

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements