Copying Arrays and Records With Spread

Week 9’s results are in, and Nadia’s script never applies them to the confirmed table. Rovers beat Albion 4-1, but until the committee agrees, that win only goes into a copy. So before you port the line that builds the provisional table, you need to know how to make a copy in JavaScript.

Python gives you several spellings for a copy of a list or a dict. JavaScript has a common spelling for arrays and plain objects, and another for Maps and Sets. In this lesson, you’ll copy the league’s data the JavaScript way. Start with the table itself.

Copy the Table and a Record With Three Dots

In Python, any of the usual spellings gives a new list of the same six team dicts:

Language: Python
provisional = table.copy()  # or list(table), or table[:]
print(provisional is table, provisional[0] is table[0])

It prints False True. In JavaScript, you write three dots inside a new array literal, much as Python’s [*table] uses a star. The brackets build a new array, and ...table spreads the table’s items into it. Here’s the confirmed table after week 8, with its copy:

Language: JavaScript
const table = [
  { team: "Albion", played: 8, points: 7, scored: 13,
    conceded: 19, form: ["L", "L", "D", "W", "L"] },
  { team: "Athletic", played: 8, points: 15, scored: 22,
    conceded: 16, form: ["W", "W", "D", "W", "W"] },
  { team: "Dynamo", played: 8, points: 10, scored: 17,
    conceded: 18, form: ["L", "L", "W", "D", "L"] },
  { team: "Rovers", played: 8, points: 13, scored: 23,
    conceded: 17, form: ["W", "L", "D", "W", "L"] },
  { team: "United", played: 8, points: 9, scored: 15,
    conceded: 21, form: ["L", "W", "L", "L", "W"] },
  { team: "Wanderers", played: 8, points: 12, scored: 17,
    conceded: 16, form: ["W", "D", "L", "W", "W"] },
];

const provisional = [...table];
console.log(provisional.length);
console.log(provisional === table);
console.log(provisional[0] === table[0]);

For objects and arrays, === asks the same question as Python’s is, though for numbers and strings it compares values, like ==. So the identity checks match Python’s, with the array length printed first:

Language: Program Output
6
false
true

The copy is a new array holding the same six records. table.slice() makes the same copy, but spread is more common. Watch out for porting table.copy() as written, because JavaScript arrays and objects have no copy() method, so the call throws TypeError: table.copy is not a function.

You copy a record the same way, with three dots inside a new object literal. Python’s dict(rovers) or {**rovers} becomes { ...rovers }. For the provisional table, you also want Rovers’ record with the win’s three points added, which Python writes as {**rovers, "points": 16}:

Language: JavaScript
const rovers = {
  team: "Rovers", played: 8, points: 13, scored: 23,
  conceded: 17, form: ["W", "L", "D", "W", "L"],
};

const updated = { ...rovers, points: 16 };
console.log(updated.points, rovers.points);

Rovers’ confirmed record keeps its 13 points:

Language: Program Output
16 13

JavaScript writes the properties in order, and a later one replaces an earlier one with the same name, so points: 16 after the dots wins. That’s the same rule as in Python’s dict display. Spread can also merge objects.

Copy Maps and Sets With Their Constructors

The table isn’t the only data the evening produces. Nadia keeps the suspended players in a set, and Tom Diaz’s red card tonight belongs in the provisional set only. In Python, set(suspended) makes the copy:

Language: Python
suspended = {"Joe Evans"}
provisional_suspended = set(suspended)
provisional_suspended.add("Tom Diaz")

Object spread copies only an object’s properties, and a Set’s entries aren’t properties, so spreading a Set into braces won’t copy it. Instead, you hand the original to the constructor, as in Python, but with new in front, which Map and Set require. The same approach works for tonight’s pitches, a Map from pitch number to home team. In Python, you’d copy the corresponding dict with dict(pitches):

Language: JavaScript
const pitches = new Map([[1, "Rovers"], [2, "Athletic"], [3, "Dynamo"]]);
const pitchesCopy = new Map(pitches);
console.log(pitchesCopy === pitches, pitchesCopy.get(1));

const suspended = new Set(["Joe Evans"]);
const provisionalSuspended = new Set(suspended);
provisionalSuspended.add("Tom Diaz");
console.log(suspended.size, provisionalSuspended.size);
console.log([...provisionalSuspended].join(", "));

The pitches copy is a separate Map with the same entries, and the red card lands in the copy and nowhere else:

Language: Program Output
false Rovers
1 2
Joe Evans, Tom Diaz

Each constructor copies its own kind. new Set() takes any iterable, anything for...of can loop over. new Map() takes [key, value] pairs, which another Map supplies. Array spread walks an iterable too, which is how [...provisionalSuspended] turns the Set into an array for .join().

Object spread doesn’t, which is why it can’t copy the Set. Watch out for copying a Map with { ...pitches } the way {**pitches} copies a dict, because a Map’s entries aren’t properties either, so you get an empty object, {}, and no error.

See How Deep the Copies Go

Every copy so far has a new outer container, but what about its contents? Here’s the Rovers record again:

Language: JavaScript
const rovers = {
  team: "Rovers", played: 8, points: 13, scored: 23,
  conceded: 17, form: ["W", "L", "D", "W", "L"],
};

const updated = { ...rovers, points: 16 };
console.log(updated.form === rovers.form);

The two records share one form array:

Language: Program Output
true

Each copy you’ve made is a shallow copy, one level deep, exactly as in Python, where {**rovers}["form"] is rovers["form"] is also True. The copy has its own properties, but a property that holds an array or an object points at the same one. So a JavaScript developer writes [...table] for an array, { ...rovers } or { ...rovers, points: 16 } for a record, and new Map() or new Set() around a collection, knowing that each copies only the top level.

Next up is the video Keeping the Confirmed Table With structuredClone(). You’ll port the line that applies the evening’s results to a working copy of the table, see what a one-level copy means for records that change, and copy every level so the confirmed table stays as it was.

Become a Member to join the conversation.