Copying, Freezing, and Sorting JavaScript Arrays for Pythonistas (Summary)

Congratulations, you made it to the end of the course! Nadia’s league table script now runs in JavaScript, ready for the booking site. league-table.js prints the same nine lines as league_table.py, from “Week 9 table (provisional)” with Rovers on top, down to the what-if line for the postponed match, “If Albion beat United 1-0: Albion 10 pts, place 5”.

And because the script works on a copy, the confirmed table still has Athletic on top, as it should until the committee confirms week 9’s results. In this course, you learned how to:

  • Copy the table with [...table], a record with { ...rovers } or { ...rovers, points: 16 }, and the pitches and suspensions with new Map(pitches) and new Set(suspended)
  • Copy every level, including records and form arrays, with structuredClone(), where Python uses copy.deepcopy()
  • Freeze tuple-like data such as POINTS with Object.freeze(), freeze a spread copy when the original must remain mutable, and check whether an object is frozen with Object.isFrozen()
  • Sort records with a compare function that takes two teams, such as (a, b) => b.points - a.points, where Python passes a key function
  • Break ties by chaining comparison results with ||, and trust a stable sort to keep teams that compare as equal in their original array order
  • Create a new, unfrozen, shallow copy with .toSorted(), .toSpliced(), and .with(), leaving the original array, frozen or not, unchanged and retaining shared records

Habits to Keep

First, ask how deep a copy must go. Spread, like Python’s table.copy(), copies one level, so it’s enough when the code only adds, removes, or reorders items. When the code changes the records themselves, as record() does with the evening’s results, reach for structuredClone(). It suits this table’s plain records and arrays, but unlike copy.deepcopy(), it can’t clone functions.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.