What is JavaScript Array flat() Method? JavaScript Tutorials in Hindi | JS Interview Question #1
We will learn how to make flatten an array in JavaScript. ES2019 introduced a new flat() method that is very helpful to flattens an arrays. And there’s a depth parameter (Infinity), So we can pass in any levels of nesting array. This is frontend developer interview question. In JavaScript Tutorials in Hindi series we will cover all the important JS Interview Question.
The flat()
method is a built-in function in JavaScript that is used with arrays to “flatten” nested arrays into a single-level array. It allows you to convert a multi-dimensional array into a one-dimensional array, removing any nested array structure.
The flat()
method does not modify the original array but instead returns a new array with the flattened elements. It can also take an optional argument, which specifies the depth level of flattening. By default, it flattens to a depth of 1, meaning it flattens one level of nested arrays.
Here’s the basic syntax of the flat()
method:
javascriptCopy codeconst flattenedArray = arrayToFlatten.flat([depth]);
arrayToFlatten
: The original array that you want to flatten.depth
(optional): The depth level to which you want to flatten the array. If not provided, it defaults to 1.
Example:
javascriptCopy codeconst nestedArray = [1, 2, [3, 4, [5, 6]], 7, [8, 9]];
const flattenedArray = nestedArray.flat();
console.log(flattenedArray); // Output: [1, 2, 3, 4, [5, 6], 7, 8, 9]
const deeplyFlattenedArray = nestedArray.flat(2);
console.log(deeplyFlattenedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this example, the flat()
method is used to flatten the nestedArray
to a depth of 1, resulting in some nested arrays still remaining. When the flat(2)
is used, it flattens the array to a depth of 2, which completely removes all the nested arrays and creates a one-dimensional array with all the elements.