Sort an array of book objects in JavaScript
Intermediate · 3 min read
Sorting a list of objects is something almost every app does: products by price, messages by date, books by ID or by author. JavaScript's sort can do all of it, once you know how to tell it what "comes first" means.
In this tutorial you will sort a list of books by their library ID, up and down, and then by author name. You will learn compare functions, why sort needs a copy, and the strange thing sort does to numbers when you don't give it a compare function. You need to know arrays, objects and arrow functions.
The data
const library = [
{ title: 'The Road Ahead', author: 'Bill Gates', libraryID: 1254 },
{ title: 'Walter Isaacson', author: 'Steve Jobs', libraryID: 4264 },
{ title: 'Mockingjay: The Final Book of The Hunger Games', author: 'Suzanne Collins', libraryID: 3245 },
];
console.log(library.map((b) => b.libraryID)); // [ 1254, 4264, 3245 ]
map here pulls out just the IDs, so you can see the order at a glance.
How a compare function works
sort takes a function that receives two items, a and b, and returns a number:
- below 0:
agoes first - above 0:
bgoes first - 0: keep them as they are
For numbers, a - b gives exactly that. If a is smaller, the result is negative and a goes first, so the list ends up smallest to largest.
Here is the exercise. Read the hints if you get stuck, or follow the steps below.
10 Sort an array of objects
fairSort a list of books. The expected output is inconsistent, so part of this exercise is working out what it must have meant.
Stuck? Three hints, smallest first
- 1.
sortmodifies the array in place and also returns it. Copy first. - 2. Subtract for numbers; use
localeComparefor text. - 3. Look at the order of the IDs in the expected output: 4264, 3245, 1254.
Step 1: sort a copy by ID
const byNumber = (list, key) => list.slice().sort((a, b) => a[key] - b[key]);
console.log(byNumber(library, 'libraryID').map((b) => b.libraryID)); // [ 1254, 3245, 4264 ]
console.log(library.map((b) => b.libraryID)); // [ 1254, 4264, 3245 ]
a[key] reads the property whose name is stored in key, so the same function can sort by any number field.
The slice() matters. sort rearranges the array you call it on, and also returns it. Without the copy, the caller's library would be reordered too. The second line shows it is untouched.
Step 2: work out the order the task wants
The expected output in the task can't be read literally: two of its books have the author and title swapped. The part you can trust is the order of the IDs, 4264, then 3245, then 1254. That is largest first, so the task wants descending order. Flip a and b:
const byNumberDesc = (list, key) => list.slice().sort((a, b) => b[key] - a[key]);
console.log(byNumberDesc(library, 'libraryID').map((b) => b.libraryID)); // [ 4264, 3245, 1254 ]
Step 3: sort by text
You can't subtract two strings. For text, use localeCompare, which returns a negative number, zero or a positive number, just like a compare function needs:
console.log('apple'.localeCompare('banana', 'en')); // -1
const byText = (list, key) => list.slice().sort((a, b) => a[key].localeCompare(b[key], 'en'));
console.log(byText(library, 'author').map((b) => b.author)); // [ 'Bill Gates', 'Steve Jobs', 'Suzanne Collins' ]
console.log(byText(library, 'title')[0].title); // Mockingjay: The Final Book of The Hunger Games
The 'en' tells it to use English sorting rules. Without a locale, the result can depend on the settings of the computer running the code.
Step 4: the wrong turn, sort with nothing
Why not just call sort() with no function at all?
console.log([1254, 4264, 3245].slice().sort()); // [ 1254, 3245, 4264 ]
console.log([10, 9, 100].slice().sort()); // [ 10, 100, 9 ]
The first one looks fine, by luck. The second is wrong. With no compare function, sort turns every item into text and sorts the text, letter by letter. '100' comes before '9' because '1' comes before '9'. The IDs only worked because they all have four digits.
Step 5: the objects are not copied
slice() copies the list, not the books inside it. The sorted list holds the very same book objects:
const sorted = byNumber(library, 'libraryID');
console.log(sorted[0] === library[0]); // true
That is usually what you want: sorting is fast, and changing a book in one list changes it everywhere.
The full solution
The panel sorts the books by ID both ways and by author, shows the original list is unchanged, and prints what sort() with no compare function does to the IDs. Press Run to see each order.
const library = [
{ title: 'The Road Ahead', author: 'Bill Gates', libraryID: 1254 },
{ title: 'Walter Isaacson', author: 'Steve Jobs', libraryID: 4264 },
{ title: 'Mockingjay: The Final Book of The Hunger Games', author: 'Suzanne Collins', libraryID: 3245 },
];
// Copy first: sort() would reorder the caller's array.
const byNumber = (list, key) => list.slice().sort((a, b) => a[key] - b[key]);
const byNumberDesc = (list, key) => list.slice().sort((a, b) => b[key] - a[key]);
// Text needs localeCompare, and it needs an explicit locale or the result
// depends on the machine running it.
const byText = (list, key) => list.slice().sort((a, b) => a[key].localeCompare(b[key], 'en'));
console.log('by ID ascending :', byNumber(library, 'libraryID').map((b) => b.libraryID));
console.log('by ID descending:', byNumberDesc(library, 'libraryID').map((b) => b.libraryID));
console.log("<- descending is the order in the expected output");
console.log('by author :', byText(library, 'author').map((b) => b.author));
console.log('original untouched:', library.map((b) => b.libraryID));
console.log('--- and the reason to pass a comparator at all ---');
console.log('IDs sorted with no comparator:', [1254, 4264, 3245].slice().sort(), '<- text order');
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('ascending by ID', byNumber(library, 'libraryID').map((b) => b.libraryID), [1254, 3245, 4264]);
test("descending, which matches the order", byNumberDesc(library, 'libraryID').map((b) => b.libraryID), [4264, 3245, 1254]);
test('the original list is not reordered', library.map((b) => b.libraryID), [1254, 4264, 3245]);
test('sorting by author', byText(library, 'author').map((b) => b.author), ['Bill Gates', 'Steve Jobs', 'Suzanne Collins']);
test('sorting by title', byText(library, 'title')[0].title, 'Mockingjay: The Final Book of The Hunger Games');
test('an empty list sorts to an empty list', byNumber([], 'libraryID'), []);
test('one item is already sorted', byNumber([library[0]], 'libraryID').length, 1);
test('ascending and descending are exact reverses', byNumber(library, 'libraryID').map((b) => b.libraryID), byNumberDesc(library, 'libraryID').map((b) => b.libraryID).reverse());
test('sort() without a comparator compares as text', [1254, 4264, 3245].slice().sort(), [1254, 3245, 4264]);
test('which goes badly wrong on mixed magnitudes', [10, 9, 100].slice().sort(), [10, 100, 9]);
test('the sorted list holds the same objects, not copies', byNumber(library, 'libraryID')[0] === library[0], true);
The expected output has author: "Walter Isaacson", title: "Steve Jobs" — the two fields swapped, and the same again in the third entry. So it cannot be taken literally. What it does show reliably is the ID order: 4264, 3245, 1254, which is descending by libraryID, and that is what the assertion checks.
Two habits to keep from this. sort() mutates, so list.slice().sort(...) unless you actually want the original reordered. And with no comparator, sort() converts everything to strings — the assertion showing [10, 9, 100] becoming [10, 100, 9] is not a contrived example, it is what happens to any list of numbers of differing lengths.
Common mistakes
- Sorting the original array.
library.sort(...)reorderslibraryitself. Copy first withslice(), or usetoSortedwhere it is available. - Leaving out the compare function for numbers.
sort()compares as text, so[10, 9, 100]becomes[10, 100, 9]. - Subtracting strings.
'Bill' - 'Steve'isNaN, andsortcan't use it. UselocaleCompare.
Try it yourself
- Sort the books by title, Z to A.
- Write
sortBy(list, key)that useslocaleComparewhen the values are strings and subtraction when they are numbers. - Sort by title length, shortest first.