JavaScript sort() Practice: Sort Objects by Price

Product lists, leaderboards and search results all need sorting. JavaScript sorts arrays in place, which surprises many beginners, and its default order treats values as text. This exercise sorts objects by a numeric property and checks that the original array is unchanged.

Before you start: Arrays of objects, arrow functions and subtraction.

Your task

Sort the books from cheapest to most expensive without changing the original array. Print the titles on one line, then print the title of the first item in the original array to prove it did not move.

Starter code

const books = [
  { title: "Algorithms", price: 450 },
  { title: "Databases", price: 320 },
  { title: "Networks", price: 510 },
];

// Print titles from cheapest to most expensive, then books[0].title.

Expected result

Databases, Algorithms, Networks
Algorithms
Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Copy the array with the spread operator, then sort the copy with a function that returns a.price minus b.price.

Show the complete solution and walkthrough
const books = [
  { title: "Algorithms", price: 450 },
  { title: "Databases", price: 320 },
  { title: "Networks", price: 510 },
];

// Print titles from cheapest to most expensive, then books[0].title.
const sorted = [...books].sort((a, b) => a.price - b.price);
console.log(sorted.map(book => book.title).join(", "));
console.log(books[0].title);
  1. Create a copy with [...books]. The copy has the same objects in the same order, but sorting it will not reorder the original array.
  2. Sort the copy with (a, b) => a.price - b.price. A negative result keeps a before b, so lower prices move to the front.
  3. Map the sorted books to their titles and join them for the first line. Print books[0].title second; it is still Algorithms.

A common mistake

Calling books.sort() without a comparator compares values as strings, so 1000 would be placed before 200. Sorting books directly also changes the original array.

Try an edge case

Books with equal prices keep their relative order in modern engines because sort is stable. An empty array stays empty.

Take it one step further

Sort from most to least expensive by swapping a and b. Then sort alphabetically by title using localeCompare.

Read the javascript tool guide