flat and flatMap
flat and flatMap are ES2019. The original nested is unchanged; the console shows [Array] for arrays nested more than three levels deep. flatMap returning [] drops an item.
An array can hold other arrays, which gives you grids and tables (2D arrays) read with two indexes like grid[row][col]; flat removes levels of nesting and flatMap maps and flattens one level in a single step.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Create a 3×3 multiplication table as a 2D array (table[r][c] is (r + 1) * (c + 1)) and print the middle row.
Given const orders = [["pen", "cap"], ["bag"], []];, make one list of all items and count them.
Explain it without notes
How do you read and loop over a 2D array?
Why does new Array(3).fill([]) cause bugs, and how do you build a grid correctly?
What is the difference between flat and flatMap?
How would you transpose a matrix in JavaScript?
Console
(nothing was printed)Expected console output
[ 1, 2, [ 3, [ 4 ] ] ]
[ 1, 2, 3, [ 4 ] ]
[ 1, 2, 3, 4 ]
[ 1, [ 2, [ 3, [Array] ] ] ]
[ 1, 3 ]
[ [ 'hello', 'world' ], [ 'hi', 'there' ] ]
[ 'hello', 'world', 'hi', 'there' ]
[ 1, 10, 3, 30 ]