Pairing Up Arrays Without zip()
In this lesson, you paired the night-bus report’s timetable with the trip feed’s actual departure times, in JavaScript.
- JavaScript has no
zip(). To pair two arrays, count through the positions with a classicforloop, and read both arrays at each position with square brackets. - Python’s
zip()stops at the end of the shorter list. A counting loop stops only where its condition says. Loop up to the longer array’s.length, and the last passes read positions that the shorter array doesn’t have. - Reading a position that an array doesn’t have gives
undefined, JavaScript’s empty value, and no error. Python raises anIndexErrorthere. Inside a template literal,undefinedturns into the textundefined. - Python’s
zip()stops silently, which can hide missing data in Python too. When the lists must be the same length,zip(..., strict=True)(Python 3.10 and later) raises aValueErrorinstead. - To stop where
zip()stops, loop up to the smaller of the two lengths. Python’smin()is a built-in function. JavaScript has no globalmin(): it keepsmin(), with its other math functions, on the built-inMathobject, much like Python’smathmodule, which has nomin()of its own. Writing the stop on its own line makes your choice visible to the next reader. Math.min()takes the numbers as separate arguments. Hand it an array, and it doesn’t throw an error: it returnsNaN, JavaScript’s “not a number” value.
The finished pairing loop:
const scheduled = ["23:10", "23:30", "23:50"];
const actual = ["23:14", "23:30", "00:02", "00:10"];
const pairCount = Math.min(scheduled.length, actual.length);
for (let i = 0; i < pairCount; i++) {
console.log(`${scheduled[i]} left at ${actual[i]}`);
}