Introduction
In this lab, we will explore the concept of flattening an array up to a specified depth using JavaScript. We will learn how to use recursion, reduce, and concat methods to merge elements or arrays. By the end of this lab, you will be able to efficiently flatten arrays and manipulate nested data structures in JavaScript.
How to Flatten an Array with JavaScript
To flatten an array up to a specified depth in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
flattenfunction with two arguments:arr(the array to be flattened) anddepth(the maximum number of nested levels to be flattened). - Inside the
flattenfunction, use recursion to decrementdepthby1for each level of depth. - Use
Array.prototype.reduce()andArray.prototype.concat()to merge elements or arrays. - Add a base case for when
depthis equal to1to stop the recursion. - Omit the second argument,
depth, to flatten only to a depth of1(single flatten).
Here is the code for the flatten function:
const flatten = (arr, depth = 1) =>
arr.reduce(
(a, v) =>
a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
[]
);
You can test the flatten function with the following examples:
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
Summary
Congratulations! You have completed the Flatten Array lab. You can practice more labs in LabEx to improve your skills.