Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.9 — Nested Arrays
JavaScript · Example 2 of 3 ES2019+

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.

01

Create a 3×3 multiplication table as a 2D array (table[r][c] is (r + 1) * (c + 1)) and print the middle row.

02

Given const orders = [["pen", "cap"], ["bag"], []];, make one list of all items and count them.

Explain it without notes

01

How do you read and loop over a 2D array?

02

Why does new Array(3).fill([]) cause bugs, and how do you build a grid correctly?

03

What is the difference between flat and flatMap?

04

How would you transpose a matrix in JavaScript?

flat and flatMap ES2019+

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 ]