Programming Advanced

Use Array.flat() to Flatten Nested Arrays

Flattening nested arrays requires recursive functions or complex reduce logic. Use Array.flat(depth) to flatten arrays to specified depth in one line.

Problem

Flattening nested arrays requires recursive functions or complex reduce logic.

Solution

Use Array.flat(depth) to flatten arrays to specified depth in one line.

Benefit

Eliminates 20+ lines of recursive flattening code.

Code Example

const nested = [1, [2, 3], [4, [5, 6]]];

// Flatten one level
const flat1 = nested.flat(); // [1, 2, 3, 4, [5, 6]]

// Flatten all levels
const flat2 = nested.flat(Infinity); // [1, 2, 3, 4, 5, 6]

ES
Edrees Salih
6 hours ago

We are still cooking the magic in the way!