JS Built-ins
Algorithmsintermediate

Flatten Nested Array

πŸ“– Usage Example
function flatten(arr) {
  return arr.reduce((acc, v) =>
    acc.concat(Array.isArray(v) ? flatten(v) : v), []);
}
flatten([1, [2, [3]]]); // [1, 2, 3]

Recursively flatten nested arrays by checking each element with Array.isArray.

Flatten Nested Array

Flattening is the process of converting a nested (multi-dimensional) array into a single-dimensional array. Recursion makes this elegant: if an element is an array, recursively flatten it; otherwise, add it to the result.

function flatten(arr: any[]): any[] {
  // Return a flattened version of the nested array
}

flatten([1, [2, [3]]]) // [1, 2, 3]
flatten([1, [2, 3], 4]) // [1, 2, 3, 4]
πŸ’‘ Hints (4)
  • β€’ Use `reduce()` to build the result array.
  • β€’ For each element, check if it's an array using `Array.isArray(val)`.
  • β€’ If it's an array, recursively flatten it.
  • β€’ If not, add it to the result using `concat()`.