Sort by several keys
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return a sorted copy of `items`. `keys` lists field names in priority order; a leading minus sign, like `"-salary"`, sorts that field from high to low. Numbers compare as numbers and strings with `<` and `>`. Items that tie on every key keep their original order. Do not change `items`.
What this exercise teaches
The comparator checks each key in turn and returns as soon as one decides the order; the minus sign flips the sign of the result. Comparing with < and > keeps numbers numeric, where converting to strings would put 100 before 9.
A hint if you get stuck
Copy with `[...items]`, then `sort` with a comparator that walks the keys and returns at the first key where two items differ. `Array.prototype.sort` is stable, so ties stay in order.
This exercise is part of Pro
Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.
You create a free account first, so Pro is attached to it.
Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.