Skip to curriculum
Jump to the editor

4.12. Sort objects by several keys (last name, then first)

Medium
Topics

This question is in

4. Array utilities
20–30 min

A staff directory lists people by last name, and people who share a last name by first name. An online shop sorts products by "in stock" first, then by price from low to high. A results table lets the user click one column, then another, and expects the second click to break ties of the first. Sorting by several keys is everyday work, and it hides several traps: numbers sorted as text, missing values in odd places, and ties that come out in a different order every time.

Write sortByKeys(array, keys) in sortByKeys.js. It returns a new array sorted by the first key, then by the second key for items whose first keys are equal, and so on.

Signature

JAVASCRIPT
function sortByKeys(array, keys) // returns a new array

Each entry of keys is one of:

  • a property name, such as "last": sort by item.last, ascending;
  • a function, such as (item) => item.name.length: sort by what it returns, ascending;
  • an object { key, order }: key is a property name or a function, and order is "asc" (the default) or "desc".

Requirements

  1. Items are sorted by the first key; only items with equal first keys are sorted by the second key, and so on.
  2. Each key is ascending unless its order is "desc", and keys can mix the two orders.
  3. Keys are compared with < and >: numbers by value (9 before 10), strings by character code (capital letters before lower-case ones), dates by time.
  4. Property names, functions, and objects with either of them as key all work.
  5. A key that is undefined or null puts its item after every item with a real value for that key, in both orders.
  6. Items equal on every key keep their input order.
  7. An empty keys array gives a copy in the input order; an empty array gives [].
  8. The result is a new array; the input is not changed.
  9. Each key function is called exactly once per item.
  10. 50,000 items with two keys are sorted in well under a second.

Examples

JAVASCRIPT
const people = [
  { first: "Mia", last: "Khan" },
  { first: "Ali", last: "Khan" },
  { first: "Zoe", last: "Adams" },
];
sortByKeys(people, ["last", "first"]);
// Zoe Adams, Ali Khan, Mia Khan
JAVASCRIPT
const products = [{ name: "Lamp", stock: 0, price: 40 }, { name: "Desk", stock: 3, price: 120 }, { name: "Mug", stock: 9, price: 8 }];
sortByKeys(products, [(p) => p.stock === 0, "price"]);
// Mug, Desk, Lamp: false sorts before true, so items in stock come first
JAVASCRIPT
sortByKeys([{ n: 2 }, { n: null }, { n: 10 }], [{ key: "n", order: "desc" }]);
// [{ n: 10 }, { n: 2 }, { n: null }]: missing values last, even in "desc"

Environment

  • Plain JavaScript in a browser page; the tests call the global sortByKeys from sortByKeys.js.
  • For one key, all items have the same kind of value (all numbers, all strings, all booleans or all dates), apart from undefined and null. Arrays have no holes.
  • Array.prototype.sort may be used. Its default order compares items as strings, so it needs a comparison function here.

Hints

  1. A comparison function returns a negative number, 0 or a positive number. How can it try the next key only when the current one gives 0?
  2. sort calls the comparison function many times for the same item. How can each key be worked out only once?
  3. Flipping the result for "desc" would also flip where missing values go. Where should that check happen?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…