w3resource

JavaScript: Flatten a given array up to the specified depth

JavaScript fundamental (ES6 Syntax): Exercise-234 with Solution

Write a JavaScript program to flatten a given array up 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.
  • Omit the second argument, depth, to flatten only to a depth of 1 (single flatten).

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const flatten = (arr, depth = 1) =>
  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

console.log(flatten([1, [2], 3, 4])); 
console.log(flatten([1, [2, [3, [4, 5], 6], 7], 8], 2));

Sample Output:

[1,2,3,4]
[1,2,3,[4,5],6,7,8]

Flowchart:

flowchart: Flatten a given array up to the specified depth.

Live Demo:

See the Pen javascript-basic-exercise-234-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to flatten an object with the paths for keys.
Next: Write a JavaScript program to get the last key that satisfies the provided testing function, otherwise undefined is returned.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

includes doesn't have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

Ref: https://bit.ly/3fFFgZv