Flattening an array in JavaScript means reducing nested arrays to a specified level of depth. This is useful when working with multi-dimensional or nested data structures.
- The flat() method creates a new array by flattening nested arrays.
- The depth determines how many levels of nested arrays are flattened.
- By default, flat() flattens the array up to one level.
- Passing Infinity as the depth completely flattens an array, regardless of its nesting level.
- The original array is not modified.
The following approach can be used to flatten a given array up to a specified depth in JavaScript.
Approach: Using the flat() Method
The flat() method recursively concatenates nested arrays up to the specified depth and returns a new flattened array.
Syntax:
array.flat(depth);- array: The array that needs to be flattened.
- depth: The number of levels to flatten. It is optional and defaults to 1.
Example 1: Demonstrates flattening an array to different depths.
const arr = [1, [2, [3, [4, 5], 6], 7, 8], 9, 10];
console.log("Original Array:", arr);
const flatArrOne = arr.flat(1);
console.log(
"Array flattened to depth 1:",
flatArrOne
);
const flatArrTwo = arr.flat(2);
console.log(
"Array flattened to depth 2:",
flatArrTwo
);
const flatArrThree = arr.flat(3);
console.log(
"Array flattened to depth 3:",
flatArrThree
);
const flatArrComplete = arr.flat(Infinity);
console.log(
"Array flattened completely:",
flatArrComplete
);
Output
Original Array: [ 1, [ 2, [ 3, [Array], 6 ], 7, 8 ], 9, 10 ] Array flattened to depth 1: [ 1, 2, [ 3, [ 4, 5 ], 6 ], 7, 8, 9, 10 ] Array flattened to depth 2: [ 1, 2, 3, [ 4, 5 ], 6, 7, 8, 9, 10 ] Arr...
Example 2: Using a Variable for the Depth
The depth can also be stored in a variable when the required level of flattening is determined dynamically.
const arr = [1, [2, [3, [4, 5]]]];
const depth = 2;
const flattenedArray = arr.flat(depth);
console.log(flattenedArray);
Output
[ 1, 2, 3, [ 4, 5 ] ]
Note: The flat() method returns a new array and does not modify the original array. If the complete nested structure needs to be flattened, use flat(Infinity).