Unpacking Arrays With Destructuring

So far, runners has reached your port as seven ready-made records, and you’ve used them to list the finishers and their times. The timing company doesn’t send records, though. It sends text rows, and the Python script turns each one into a record first. Mei Chen’s row, with its stray space and missing 10 km read, makes a good test.

In this lesson, you’ll port the line of Python that takes a row apart. The port reads almost like the Python code but behaves differently when a row has the wrong shape, and that matters on a live results page.

Take a Row Apart

The Python script trims every cell, then unpacks the cells in one line. The first three get names, and the starred target collects the checkpoint and finish times into a list:

Language: Python
line = "23, Mei Chen,F35,0:22:40,,1:08:55,1:36:20"
cells = [cell.strip() for cell in line.split(",")]
bib, name, group, *splits = cells

You’ve already unpacked arrays in JavaScript, in loop headers and on the first line of toSeconds(). That’s array destructuring: brackets on the left of the = form a pattern, and each name in it takes the value at its position in the array on the right, here cells. The JavaScript port adds one new piece:

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);

The names get the first three cells, and splits gets everything after them:

Language: Program Output
23 Mei Chen F35
[ '0:22:40', '', '1:08:55', '1:36:20' ]

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.