Unpacking Arrays With Destructuring

So far, runners has reached your port as ready-made records. The timing company sends text rows, though, and the Python script unpacks each row into a record first. Porting that line is quick. How your JavaScript code handles a row of the wrong shape needs more care, because a wrong time can end up on a live results page.

Take a Row Apart

You’ve already destructured arrays in loop headers and in toSeconds(): brackets on the left of = take values by position. Here’s how Python’s unpacking lines map to JavaScript:

Python JavaScript
Collect the rest bib, name, group, *splits = cells const [bib, name, group, ...splits] = cells;
All but the last *checkpoints, finish = splits splits.slice(0, -1) and splits.at(-1)
Swap two names a, b = b, a [a, b] = [b, a]; on two let variables

The three dots mark ...splits as a rest element, which collects the remaining values into a new array, as Python’s starred target does. Try it on Mei Chen’s row, with its stray space and missing 10 km read:

Language: JavaScript
const line = "23, Mei Chen,F35,0:22:40,,1:08:55,1:36:20";
const cells = line.split(",").map((c) => c.trim());
const [bib, name, group, ...splits] = cells;

console.log(bib, name, group);
console.log(splits);

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.