In this article, we will learn how to flatten a given array up to the specified depth in JavaScript.
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:
Javascript
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,...
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Jun, 2023
Like Article
Save Article