Nested Loops with Arrays & Objects
A nested loop is a loop inside the body of another loop. The inner loop runs in full on every pass of the outer one. Nesting matches the shape of nested data: an array of arrays, such as a grid or a table, or an array of objects, where the outer loop visits each record and the inner loop visits its properties.
Arrays of arrays
Section titled “Arrays of arrays”An array whose items are arrays is often called a two-dimensional array. Two indexes reach one item: the first picks the inner array, and the second picks the item within it. The inner arrays need not be the same length, so the inner loop reads the length of the current one:
const seating = [ ['A1', 'A2', 'A3'], ['B1', 'B2'], ['C1', 'C2', 'C3', 'C4'],];
let seats = 0;for (let row = 0; row < seating.length; row++) { for (let seat = 0; seat < seating[row].length; seat++) { seats++; } console.log(`after row ${row}: ${seats} seats`);}
console.log(seating[2][3]);This prints:
after row 0: 3 seatsafter row 1: 5 seatsafter row 2: 9 seatsC4Each loop needs its own counter name. A second let i in the inner loop would hide the outer counter from the inner body, and with var the two loops would share one variable, so the outer loop would lose its place.
Where the indexes are not needed, for...of reads more simply. This averages a week of temperatures for each row:
const weeks = [ [12, 14, 11, 15, 13, 10, 9], [16, 18, 17, 19, 21, 20, 18],];
for (const [i, week] of weeks.entries()) { let total = 0; for (const temp of week) { total += temp; } console.log(`week ${i + 1} average: ${(total / week.length).toFixed(1)}`);}This prints:
week 1 average: 12.0week 2 average: 18.4total is declared inside the outer loop, so it starts again at 0 for each week.
Arrays of objects
Section titled “Arrays of objects”For a list of records, the outer loop visits each object and an inner for...in loop visits that object’s properties:
const team = { name: 'Support', members: [ { name: 'Ana', role: 'lead', shift: 'early' }, { name: 'Ben', role: 'agent', shift: 'late' }, ],};
for (const member of team.members) { console.log(member.name); for (const key in member) { if (key !== 'name') { console.log(` ${key}: ${member[key]}`); } }}This prints:
Ana role: lead shift: earlyBen role: agent shift: lateInside the inner loop, the property name is held in the variable key, so the value must be read with bracket notation. Dot notation looks for a property literally named key:
const member = { name: 'Ana', role: 'lead' };const key = 'role';
console.log(member[key]);console.log(member.key);This prints:
leadundefinedLeaving both loops at once
Section titled “Leaving both loops at once”break ends only the loop it is in. To leave the outer loop from inside the inner one, put a label before the outer loop and name it in the break:
const grid = [ [3, 8, 1], [6, 0, 4], [7, 2, 5],];
search: for (let r = 0; r < grid.length; r++) { for (let c = 0; c < grid[r].length; c++) { if (grid[r][c] === 0) { console.log(`found 0 at row ${r}, column ${c}`); break search; } console.log(`checked ${grid[r][c]}`); }}This prints:
checked 3checked 8checked 1checked 6found 0 at row 1, column 1Labels are uncommon in everyday code. Moving the loops into a function and using return does the same job and is often easier to read.
When a nested loop is not needed
Section titled “When a nested loop is not needed”Nested loops multiply: an outer loop of 1,000 items around an inner loop of 1,000 items runs the inner body a million times. Where the goal is only to flatten the data, flat() does it in one call:
const grid = [[3, 8, 1], [6, 0, 4]];console.log(grid.flat());This prints:
[ 3, 8, 1, 6, 0, 4 ]Likewise, where an inner loop searches one array for each item of another, building a Set or Map of the second array first replaces the inner loop with a single lookup. Array flat and Maps and Sets cover these.
Steve Griffith covers this topic in his video JavaScript Nested Loops with Arrays and Objects.