In Order of Time

A lineup should go in the order the bands play, but in bands.js, the bands are in the order they signed up. You know sorting from the JavaScript course: sort() with a compare function. Times are texts, so compare them with localeCompare():

const byTime = [...bands].sort((a, b) => a.time.localeCompare(b.time));

Texts are compared character by character, so times sort right as long as they all have the same form: "09:00" comes before "18:30", but "9:00" would come after it, because 9 comes after 1. Our times always have two digits for the hour.

Why [...bands]? sort() doesn't make a new array, it sorts the array itself. Here, that's bands, which the whole app imports from bands.js. A component that sorted it would change the order for every other component too, just by being rendered. Components don't change the data they get: they only look at it and show it. (In the lessons about state, you'll see that React wouldn't even notice such a change.) So sort a copy: spread makes one, and sort() sorts only the copy.

The sorted copy can then be filtered, and the bands of each day stay in the order of time. It works the other way around too: filter() makes a new array, so its result may be sorted without a copy. bands.filter(…).sort(…) changes only the new array.

A typical mistake is bands.sort(…) without a copy. The page may look right, but the array in bands.js is now sorted too, and every other part of the app gets it in this order.

Instructions

Show each day's bands in the order they play, the earliest first: before the filters, sort a copy of bands by time into a constant byTime, and filter the days from it.

At the end of the page, add a section with the heading A to Z and a list ul of the names of all the bands in alphabetical order.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

6/11

Next