How to Flatten a Given Array up to Specified Depth in JavaScript?
Flatten an array in JavaScript is a common task when dealing with nested arrays. The concept of "flatten" means to convert a multi-dimensional array into a single-dimensional array. When you need to control the depth of flattening, JavaScript provides methods to handle this efficiently. This process involves reducing the array’s depth up to a specified level, which allows for a more flexible and manageable data structure, especially when dealing with complex or deeply nested arrays. In this article, we will learn how to flatten a given array up to the specified depth in JavaScript.
Understanding of Flatten Array
Array flattening is the process of converting a multi-dimensional array into a single-dimensional array. For instance, consider the following array:
const array = [1, [2, [3, [4, 5]]]];
Flattening this array completely would result in:
const flattenedArray = [1, 2, 3, 4, 5];
Flattening an Array up to a specific depth means only flattening up to a certain level of nested arrays. For example, flattening to a depth of 2 would result in:
const partiallyFlattenedArray = [1, 2, [3, [4, 5]]];
The flat() method in JavaScript is used to flatten an array up to the required depth. It creates a new array and recursively concatenates the sub-arrays of the original array up to the given depth. The only parameter this method accepts is the optional depth parameter (by default: 1). This method can be also used for removing empty elements from the array.
Syntax
array.flat(depth);
Example: Flattening an Array in multiple depth.
// Define the array
let arr = [1, [2, [3, [4, 5], 6], 7, 8], 9, 10];
console.log("Original Array:", arr);
let flatArrOne = arr.flat();
console.log("Array flattened to depth of 1:" + flatArrOne);
let flatArrTwo = arr.flat(2);
console.log("Array flattened to depth of 2:" + flatArrTwo);
let flatArrThree = arr.flat(Infinity);
console.log("Array flattened completely:" + flatArrThree);
Output
Original Array: [ 1, [ 2, [ 3, [Array], 6 ], 7, 8 ], 9, 10 ] Array flattened to depth of 1:1,2,3,4,5,6,7,8,9,10 Array flattened to depth of 2:1,2,3,4,5,6,7,8,9,10 Array flattened completely:1,2,3,4,5,...