YouTip LogoYouTip

Jsref Flat Array

## JavaScript Array flat() Method The `flat()` method is a built-in JavaScript Array method that creates a new array with all sub-array elements concatenated into it recursively up to a specified depth. This method is non-mutating, meaning it does not modify the original array but instead returns a brand-new array. --- ## Syntax ```javascript flat() flat(depth) ``` ### Parameters | Parameter | Description | | :--- | :--- | | `depth` *(Optional)* | A number specifying how deep a nested array structure should be flattened. Defaults to `1`. | ### Return Value * **Type:** `Array` * **Description:** A new array containing the sub-array elements concatenated into it. ### Technical Details * **ECMAScript Version:** ES2019 (ES10) * **Mutates Original Array:** No (it returns a shallow copy containing the flattened elements). --- ## Browser Support The numbers in the table specify the first browser version that fully supports the `flat()` method: | Method | Chrome | Edge | Firefox | Safari | Opera | | :--- | :--- | :--- | :--- | :--- | :--- | | `flat()` | 69.0 | 79.0 | 62.0 | 12.0 | 56.0 | --- ## Code Examples ### 1. Basic Flattening (Default Depth of 1) If no depth argument is provided, `flat()` defaults to a depth of `1`. ```javascript const nestedArray = [1, 2, [3, 4, [5, 6]]]; const flatArray = nestedArray.flat(); console.log(flatArray); // Output: [1, 2, 3, 4, [5, 6]] ``` ### 2. Specifying a Custom Depth You can pass an integer to specify exactly how many levels of nesting you want to flatten. ```javascript const deeplyNestedArray = [1, 2, [3, 4, [5, 6]]]; const deeplyFlatArray = deeplyNestedArray.flat(2); console.log(deeplyFlatArray); // Output: [1, 2, 3, 4, 5, 6] ``` ### 3. Flattening Infinitely Nested Arrays If you do not know the depth of the nested arrays but want to flatten them completely into a single-dimensional array, you can pass `Infinity` as the depth argument. ```javascript const complexArray = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; const fullyFlatArray = complexArray.flat(Infinity); console.log(fullyFlatArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` ### 4. Handling Empty Slots in Arrays The `flat()` method automatically removes empty slots (sparse arrays) during the flattening process. ```javascript const sparseArray = [1, 2, , 4, 5]; const cleanedArray = sparseArray.flat(); console.log(cleanedArray); // Output: [1, 2, 4, 5] ``` --- ## Key Considerations * **Immutability:** The `flat()` method does not change the original array. It always returns a new array. * **Sparse Arrays:** It is a highly efficient way to clean up empty slots in an array, even if the array is already flat (e.g., `[1, , 2].flat()` returns `[1, 2]`). * **Performance:** Flattening extremely large arrays with a high depth or using `Infinity` can be resource-intensive. Use it mindfully in performance-critical applications.
← Python Ai DrawJsref Of Array β†’