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(). Count through the positions with a classicforloop, and read both arrays at each position with square brackets. - A counting loop stops only where its condition says, not at the end of the shorter array, as
zip()does. Count up to the longer array’s.length, and the last passes read positions the shorter array doesn’t have. - A missing position gives
undefined, with no error, where Python raises anIndexError. A template literal turns it into the textundefined. - To stop where
zip()stops, count up to the smaller length, worked out on its own line so the next reader sees the choice. JavaScript has no globalmin(): it lives on the built-inMathobject.
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]}`);
}