JavaScript: Flatten a given array up to the specified depth
JavaScript fundamental (ES6 Syntax): Exercise-234 with Solution
Flatten Array to Depth
Write a JavaScript program to flatten a given array to the specified depth.
- Use recursion, decrementing depth by 1 for each level of depth.
- Use Array.prototype.reduce() and Array.prototype.concat() to merge elements or arrays.
- Base case, for depth equal to 1 stops recursion.
- Write a JavaScript program to flatten a given array to the specified depth.
Sample Solution:
JavaScript Code:
// Define a function 'flatten' that flattens nested arrays up to a specified depth
const flatten = (arr, depth = 1) =>
arr.reduce((a, v) =>
a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
// Test the 'flatten' function with sample arrays
console.log(flatten([1, [2], 3, 4])); // Output: [1, 2, 3, 4]
console.log(flatten([1, [2, [3, [4, 5], 6], 7], 8], 2)); // Output: [1, 2, 3, [4, 5], 6, 7, 8]
Output:
[1,2,3,4] [1,2,3,[4,5],6,7,8]
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-234-1 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript program that flattens an array to a specified depth using recursion.
- Write a JavaScript function that takes a nested array and returns a new array flattened to the given level.
- Write a JavaScript program that implements a custom flatten function with a depth parameter, without using flat().
- Write a JavaScript function that reduces nested arrays to a one-dimensional array up to a specified depth.
Go to:
PREV : Flatten Object Keys as Paths.
NEXT : Last Key Satisfying Condition.
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.