Sort by Several Keys
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Write sortBy(items, keys): return a new, sorted array and leave items alone. keys is a list, and each key is one of three things: a property name, which sorts ascending; the same name after a minus sign, like minus age, which sorts descending; or a function that takes an item and returns the value to sort by, ascending. Sort by the first key, and use each later key only to break ties left by the ones before it. Items that tie on every key keep their original order, in both directions. Under one key the values are all numbers or all strings, compared with less-than and greater-than, except that an item missing the value, so undefined, always goes after the others, ascending or descending.
Your code must pass
- Sorts by one property, ascending
- Sorts descending with a minus sign
- Breaks ties with the later keys
- Accepts functions as keys
- Keeps tied items in their original order
- Puts missing values last in either direction
- Returns a new array and leaves the input alone