Lessons · TypeScript · zip (walk two lists)
Walking two arrays together
Loop by index and read both arrays at position i, or map one array using the index to reach into the other.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Names and scores, timestamps and readings, headers and cells: parallel arrays are everywhere.
How to think about it
Am I indexing two arrays with the same i? Then either a plain index loop, or names.map((name, i) => ...scores[i]...). Check the lengths match first.
Worked example
const names = ["ada", "bo"], scores = [90, 72];Parallel.
names.map((name, i) => `${name}: ${scores[i]}`);["ada: 90", "bo: 72"]: the index reaches into the second array.Object.fromEntries(names.map((n, i) => [n, scores[i]]));{ada: 90, bo: 72}: pairs make an object directly.
Your turn
Add pairs position by position.
const sums = a.map((x, ) => x + b[]);
Solve one with the tests running
The trap
If the arrays differ in length, b[i] is undefined past the end and the sum is NaN, silently.
Practise zip (walk two lists) on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.