Code Lab

Three smallest numbers

MediumArrays10 min

Write a function threeSmallest(numbers) that returns the three smallest numbers of an array.

  • numbers is an array of integers. They can be positive, negative or 0.
  • Return a new array with the three smallest numbers, from small to large.
  • Equal numbers count separately: [3, 3, 1] gives [1, 3, 3].
  • If the array has fewer than 3 numbers, return all of them, from small to large. An empty array gives [].
  • Compare the numbers by value: 10 is larger than 9.
  • Do not change the input array.

If you sort, keep in mind that sort changes (mutates) the array it is called on and needs a compare function to sort numbers by value.

Examples

threeSmallest([5, 1, 4, 2, 3])

Returns [ 1, 2, 3 ]

threeSmallest([3, 3, 1])

Returns [ 1, 3, 3 ]

threeSmallest([8, 2])

Returns [ 2, 8 ]

Source

Loading the editor...
  1. InputthreeSmallest([ 5, 1, 4, 2, 3 ])
    Expected[ 1, 2, 3 ]
  2. InputthreeSmallest([ 3, 3, 1 ])
    Expected[ 1, 3, 3 ]
  3. InputthreeSmallest([ 8, 2 ])
    Expected[ 2, 8 ]

Hidden tests run on Submit.