Sort a table by several columns
Click a table header and you sort by one column. Shift-click another and you sort by both: the second column only breaks ties in the first. Writing that as a single comparator is the trick.
Implement sortBy(items, sorts). items is an array of objects. sorts is an array of { key, direction } objects, applied in order: the first entry is the primary sort, the second breaks its ties, and so on. direction is either "asc" or "desc", and defaults to ascending when it is absent. Compare values with the < and > operators, so numbers sort numerically and strings sort lexicographically. Return a new array; the input must not be reordered. The sort is stable: items that compare equal on every key stay in their original relative order. An empty sorts array returns a copy of items in its original order.
What it has to do
- Apply the sorts in order, using later entries only to break ties.
- Support
direction: "desc", defaulting to ascending whendirectionis absent. - Compare with
<and>so numbers sort numerically and strings lexicographically. - Be stable: items equal on every key keep their original relative order.
- Return a new array and leave the input array's order untouched.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.