Spreading Arrays and Objects
In this lesson, you ported the lines of the race results script that join, print and copy with *
and **. In JavaScript, three dots do the work of both.
- In square brackets, three dots spread an iterable’s items, as Python’s
*does in a list:[*wave_one, *wave_two]becomes[...waveOne, ...waveTwo], one array of all seven runners. It’s the same spread aspush(...waveTwo),[...new Set(...)]and[..."F35"], which gives[ 'F', '3', '5' ]. - In a call, they pass each item as its own argument:
print("Missing chip reads:", *missing)becomesconsole.log("Missing chip reads:", ...missing), and both printMissing chip reads: 23 58. Without the dots, both print the list itself. - In braces, three dots copy an object’s properties, as
**does in a dict:{**runner, "checkpoints": […]}becomes{ ...runner, checkpoints: […] }. The later key wins, andrunneritself keeps its gap. As in Python, the copy is shallow:{ ...runner }sharesrunner’s checkpoints array. Replacing it is safe, but pushing a read onto it changesrunnertoo. - A plain object isn’t iterable, so
[...times], the port of Python’s[*times], stops withTypeError: times is not iterable. A plain object spreads only into another object, such as{ ...times }. - Ask for the one you mean:
Object.keys(times)for the keys, which come back as strings (fine for listing bibs),Object.values(times)for the values, orObject.entries(times)for the[key, value]pairs. A Map, such astimesMap = new Map(finishers.map((r) => [r.bib, r.finish])), keeps number keys, but[...timesMap]spreads into pairs, like Python’s[*times.items()], not into keys like[*times]. - Spreading numbers into
Math.min()comes later in the course.
Here’s the port, with the two waves’ timing lines written out and Python’s [*times] asked for
by name:
const WAVE_ONE = [
"7,Ana Ruiz,F35,0:24:10,0:48:35,1:13:02,1:42:37",
"12,Tom Okafor,M40,0:21:05,0:42:30,1:04:12,1:30:48",
"23, Mei Chen,F35,0:22:40,,1:08:55,1:36:20",
"31,Lars Berg,M40,0:23:15,0:47:01,,DNF",
];
const WAVE_TWO = [
"44,Priya Nair,F20,0:20:30,0:41:10,1:02:05,1:27:44",
"58,Sam Kowalski ,M40,0:22:50,0:45:12,,1:35:03",
"66,Jo Lindqvist,F20,0:23:30,0:47:55,1:12:40,1:41:15",
];
function toRecord(line) {
const [bib, name, group, ...splits] = line
.split(",")
.map((c) => c.trim());
return {
bib: Number(bib),
name,
group,
checkpoints: splits.slice(0, -1),
finish: splits.at(-1),
};
}
const waveOne = WAVE_ONE.map(toRecord);
const waveTwo = WAVE_TWO.map(toRecord);
const runners = [...waveOne, ...waveTwo];
const finishers = runners.filter((r) => r.finish !== "DNF");
const missing = finishers
.filter((r) => r.checkpoints.includes(""))
.map((r) => r.bib);
console.log("Missing chip reads:", ...missing);
const runner = runners[2];
const fixed = {
...runner,
checkpoints: ["0:22:40", "0:45:58", "1:08:55"],
};
const times = Object.fromEntries(
finishers.map((r) => [r.bib, r.finish]),
);
const bibs = Object.keys(times);
console.log(bibs);