CyberStars

sort Changes the Array

Sort the books on your shelf by color, and the old order, by writer, is gone. If you wanted both, you should have written down the old order first. sort is like moving the books on the shelf: it changes the array itself.

sort changes the array

function youngestFirst(a, b) {
  return a - b;
}

const ages = [13, 9, 15];
const sorted = ages.sort(youngestFirst);
console.log(sorted);
console.log(ages);
[9, 13, 15]
[9, 13, 15]

Both are sorted! Not like filter, sort doesn't make a new array. It changes the order of the array you call it on, and gives back that same array. sorted and ages are two names for one list.

That's a trap when another part of your script still needs the first order: the flights in the order of the board, or the players in the order they joined.

Sort a copy

To keep the first order, sort a copy. slice(), with nothing in its brackets, makes a copy of an array:

const sorted = ages.slice().sort(youngestFirst);
console.log(sorted);
console.log(ages);
[9, 13, 15]
[13, 9, 15]

ages.slice() is a new array with the same items. Sorting it doesn't change ages.

Break it on purpose

Make a "copy" by giving the array a second name:

const copy = ages;
copy.sort(youngestFirst);
console.log(ages);
[9, 13, 15]

It's still sorted. const copy = ages doesn't copy anything. It's a second name for the same list, like two labels on one jar. Only slice() makes a real copy.


Mission: Keep the board's order

What you will see: when schedule.html opens, #last-departure still says Last departure: SL-104 at 11:00, and the console shows:

First on the board: SL-101
Earliest: SL-103

Your script sorted flights to find the last departure, and lost the board's order. The rest of the script needs both.

  • flights keeps the order of the board.
  • The sorting is done on a copy.
  • The console shows First on the board: , then the code of the first item of flights.
  • The console shows Earliest: , then the code of the first item of the sorted copy.
  • #last-departure stays as it was.