Javascript Fundamentals · Array Methods

Sort without mutating

non-mutating sort

Sort without mutating

You have a list of players and you want the highest scorer first. sort puts an array in order — but the built-in Array.prototype.sort mutates the array in place, and its default order is by string, not by number: [10, 9, 1].sort() gives [1, 10, 9], because "10" sorts before "9".

toSorted is the non-mutating twin: it returns a new, ordered array and leaves the original untouched.

const numbers = [10, 9, 1, 2];

numbers.sort((a, b) => a - b); // numbers is now [1, 2, 9, 10]
const ranked = numbers.toSorted((a, b) => a - b); // a new array; numbers is untouched

The comparator follows the standard rule: it returns a negative number when the first argument should come first, a positive number when the second should, and 0 for a tie. So (a, b) => a - b orders numbers ascending, and b - a orders them descending. Always pass one — without a comparator, sort compares elements as strings.

If you need to support older engines without toSorted, copy first and sort the copy: [...array].sort(compare) gives the same non-mutating result.

Export rankByScore from index.js. Called with an array of players, it returns a new array ranked from the highest score to the lowest, leaving the input in its original order.

Challenge

You have a list of players and you want a ranking from the highest score to the lowest, without reordering the list you were handed. Export rankByScore from index.js.

It takes an array of players (objects with a score number) and returns a new array ordered from the highest score to the lowest, using the non-mutating toSorted. The players array must still hold its original order after the call.

index.js
export function rankByScore(players) {
  return players;
}

export function render(mount) {
  const players = [
    { name: 'Ada', score: 30 },
    { name: 'Grace', score: 50 },
    { name: 'Alan', score: 20 },
  ];
  const ranked = rankByScore(players);

  mount.innerHTML = `
    <p>Ranked: ${ranked.map((player) => `${player.name} (${player.score})`).join(', ')}</p>
    <p>Original: ${players.map((player) => player.name).join(', ')}</p>
  `;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.