Skip to the code
cf.
+10 XP

#217 Sort Prices as Numbers

easy

A shop's "Price: low to high" button shows products in a strange order: [10, 9, 1] becomes [1, 10, 9]. The bug is a call to prices.sort() with no compare function, which compares the numbers as strings.

Write sortPrices(prices) that returns a new array with the prices sorted from lowest to highest as numbers. Do not change the input array.

Example 1

Input: prices = [10,9,1]
Output: [1,9,10]

As numbers, 9 is less than 10. As strings, "10" would come before "9".

Example 2

Input: prices = [100,25,3.5,25]
Output: [3.5,25,25,100]

Decimals and duplicates sort normally.

Constraints

  • 0 <= prices.length <= 100000
  • -10^6 <= prices[i] <= 10^6, possibly with decimals
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).