BeginnerCoder

Lesson 9 — flat & flatMap

Flatten nested arrays

A nested array has arrays inside it, like [[1, 2], [3]]. flat() removes one level of nesting. flatMap(fn) first runs fn on every item (like map) and then flattens the results one level — handy when each item turns into several.

console.log([[1], [2, 3]].flat());            // [ 1, 2, 3 ]
console.log([1, 2].flatMap((n) => [n, n]));   // [ 1, 1, 2, 2 ]

Why it matters: data often arrives grouped (pages of results, lines of words) and you need one simple list to work with.

Want it another way?
Task

Flatten nested one level, and use flatMap to split each phrase into separate words.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.