AniUI Academy

Sort a table by several columns

mediumArrays & Objects+250 XPPractice

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. direction defaults 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 tiebreak
sortBy([{ n: 3 }, { n: 1 }, { n: 2 }], []);
// [{ n: 3 }, { n: 1 }, { n: 2 }] — no sorts means the 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 when direction is 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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.