[Solved] Smallest Two Numbers in JavaScript array of numbers

  

3
Topic starter

Write a JS function (program) that prints the two smallest elements from an array of numbers. The input comes as array of number elements.

Examples:

Input:
[30, 15, 50, 5]

Output:
5 15


Input:
[3, 0, 10, 4, 7, 3]

Output:
0 3

The output is printed on the console on a single line, separated by space.

1 Answer
2

Javascript code for this task:

function smallestTwoNumbers(arrNum) {
    let result = arrNum.sort((a, b)=>a - b)
    .slice(0,2)
    .join(" ");
    console.log(result);
}
 
smallestTwoNumbers([30, 15, 50, 5]);
Share: