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.
Arguments
itemsArray<Object>- The records to sort.
sortsArray<{ key: string, direction?: "asc" | "desc" }>- The sort stack. Earlier entries are primary; later ones only break ties.
directiondefaults to"asc".
Returns
Array<Object> — A new, stably sorted array. The input is never reordered.
Examples
sortBy(
[
{ name: "Ana", score: 8 },
{ name: "Bo", score: 10 },
{ name: "Cy", score: 8 },
],
[{ key: "score", direction: "desc" }, { key: "name" }],
);
// [{ Bo, 10 }, { Ana, 8 }, { Cy, 8 }] — score desc, name asc as tiebreaksortBy([{ n: 3 }, { n: 1 }, { n: 2 }], []);
// [{ n: 3 }, { n: 1 }, { n: 2 }] — no sorts means the original orderWhat 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.
Stuck? The javascript course covers everything this challenge needs.
- 1.sorts ascending when no direction is given
- 2.breaks ties with the second sort key
- 3.is stable for items equal on every key
- 4.returns the original order for an empty sorts array
- 5.does not reorder the input array
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.