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

Nadia’s league table script now runs in JavaScript. league-table.js prints the same nine lines as league_table.py, from “Week 9 table (provisional)” with Rovers on top to “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. Keep these JavaScript techniques handy when you port your next script that copies, protects, or sorts data:

  • Copy one level with [...table], { ...rovers }, or { ...rovers, points: 16 }, and copy a Map or Set with its constructor, new Map(pitches) or new Set(suspended).
  • Copy every level of plain data records, like those in the league table, with structuredClone(), as copy.deepcopy() does. It isn’t a general replacement for deepcopy(): a function or a symbol stops it with a DataCloneError, class instances come back as plain objects, and frozen data comes back unfrozen. Check the structured clone limits before cloning anything else.
  • Freeze tuple-like data where you create it, as in Object.freeze([3, 1, 0]), and freeze a spread copy when the original must stay mutable. Check with Object.isFrozen().
  • Sort records with a compare function in place of key=, such as (a, b) => b.points - a.points, chain tie-breakers with ||, and trust the stable sort to keep equal teams in their original order.
  • Get a changed copy with .toSorted(), .toSpliced(), or .with(). Each leaves the original, frozen or not, unchanged and returns an unfrozen copy. Like spread, it copies one level and shares the original’s records.

Keep the JavaScript Habits and Drop the Python Ones

Ask how deep a copy must go: spread is enough to reorder, but record() changes the records themselves, so the provisional table needs structuredClone(). A freeze is one level deep, so freeze each record too, and remember that const fixes only the name. For largest first, put the direction inside one named compare function, swapping a and b when comparing each numeric field.

Three Python habits went wrong in the port:

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.