JavaScript Array flat() Method is used to flatten nested arrays by combining their elements into a new array. It removes nested array levels according to a specified depth.
For example, an array may contain numbers and other arrays. Using flat() makes the nested values accessible in a single-level array.
const numbers = [1, 2, [3, 4], [5, 6]];
const result = numbers.flat();
console.log(result);
Output:
[1, 2, 3, 4, 5, 6]
By default, flat() removes one level of nesting. It returns a new array without modifying the original array.
Syntax and Formal Specification
The method signature is flat(depth).
Parameters
-
depth(optional) — The depth level specifying how deep a nested array structure should be flattened. Defaults to1. If the depth isInfinity, the array is flattened until it contains no more nested arrays .
Return Value
A new array with the sub-array elements concatenated into it. The original array is never mutated.
The Depth Parameter
The default depth of 1 is the most common source of confusion. A single call to flat() only removes one level of nesting. Deeper structures require an explicit depth or Infinity.
const arr = [1, 2, [3, 4, [5, 6]]]; console.log(arr.flat()); // [1, 2, 3, 4, [5, 6]] (depth 1) console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6] (depth 2) console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5, 6] (fully flattened)
Sparse Arrays and Empty Slots
flat() removes empty slots (holes) from the levels it flattens. This is a deliberate design choice that distinguishes it from methods like map() or filter(), which skip holes without removing them .
The behavior depends on depth. At depth = 1, holes in the root array and in the first level of nested arrays are removed. Holes in deeper nested arrays are preserved as part of those arrays because the deeper arrays themselves are not yet flattened .
// Holes removed at flattened levels const arr5 = [1, 2, , 4, 5]; // eslint-disable-line no-sparse-arrays console.log(arr5.flat()); // [1, 2, 4, 5] const mixed = [1, , 3, ["a", , "c"]]; // eslint-disable-line no-sparse-arrays console.log(mixed.flat()); // [1, 3, "a", "c"] // Deeper holes preserved when depth is insufficient const deeper = [1, , 3, ["a", , ["d", , "e"]]]; // eslint-disable-line no-sparse-arrays console.log(deeper.flat()); // [1, 3, "a", ["d", empty, "e"]] console.log(deeper.flat(2)); // [1, 3, "a", "d", "e"]
flat() vs. flatMap()
flatMap() (also ES2019) first maps each element using a callback, then flattens the result by exactly one level. It is semantically equivalent to map(fn).flat() but is more efficient because it avoids allocating the intermediate mapped array .
const duplicate = x => [x, x]; // Two passes, intermediate array allocated const viaMapFlat = [2, 3, 4].map(duplicate).flat(); // [2, 2, 3, 3, 4, 4] // One pass, fused operation const viaFlatMap = [2, 3, 4].flatMap(duplicate); // [2, 2, 3, 3, 4, 4]
The key distinction: flatMap() cannot accept a depth parameter. It always flattens exactly one level. For multi-level flattening combined with mapping, map().flat(depth) is required. Use flatMap() when the transformation naturally produces zero or more values per input and those values should be concatenated into a single result.
Using flat() with Strings and Objects
The flat() method only flattens nested arrays. It does not split strings into individual characters or change objects into separate properties.
const data = [
"JavaScript",
["HTML", "CSS"],
[{ id: 1 }, { id: 2 }]
];
const result = data.flat();
console.log(result);
Output:
["JavaScript", "HTML", "CSS", { id: 1 }, { id: 2 }]
The string remains a single element, and each object retains its properties. The method only removes the array nesting at the specified depth.
Flattening Multidimensional Arrays
A multidimensional array contains arrays inside other arrays. You can use the depth parameter to convert these structures into a single-level array.
const matrix = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
];
const result = matrix.flat(2);
console.log(result);
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
The outer array contains two nested arrays, and each of those contains additional arrays. A depth of 2 removes both nested levels.
flat() vs. Manual reduce + concat
Before flat() existed, the standard pattern was arr.reduce((acc, val) => acc.concat(val), []). This works but has a subtle performance issue: concat creates a new array at every iteration, leading to repeated reallocations. flat() is optimized in modern engines to append efficiently.
const nested = [[1, 2], [3, 4], [5, 6]]; // Legacy pattern: repeated allocation const legacy = nested.reduce((acc, val) => acc.concat(val), []); // Native: single allocation const native = nested.flat(); console.log(legacy, native); // [1,2,3,4,5,6] [1,2,3,4,5,6]
JavaScript flat() Does Not Modify the Original Array
The JavaScript flat() method creates a new array containing the elements of the original array with nested arrays flattened to the specified depth. It does not modify or overwrite the original array.
This means you can use flat() to create a flattened version of an array while keeping the original array unchanged. The original array retains its nested structure, whereas the new array contains the flattened elements.
Example: flat() Does Not Modify the Original Array
Let’s look at an example:
const numbers = [10, [20, 30], [40, 50]];
const result = numbers.flat();
console.log("Original:", numbers);
console.log("Result:", result);
Output:
Original: [10, [20, 30], [40, 50]]
Result: [10, 20, 30, 40, 50]
In this example, the numbers array contains three elements. The second and third elements are nested arrays.
When we call numbers.flat(), JavaScript creates a new array named result. By default, flat() flattens nested arrays by one level.
As a result:
- The
numbersarray remains unchanged. - The nested arrays are flattened in the new
resultarray. - The
resultarray is a separate array from the originalnumbersarray. - The original array retains its nested structure.
Modifying the Result Does Not Change the Original Array
Because flat() returns a new array, modifying the top-level structure of the returned array does not modify the original array.
const numbers = [10, [20, 30], [40, 50]];
const result = numbers.flat();
// Modify the new array
result.push(60);
console.log("Original:", numbers);
console.log("Result:", result);
Output:
Original: [10, [20, 30], [40, 50]]
Result: [10, 20, 30, 40, 50, 60]
Here, the push() method adds 60 to the new result array. It does not add the value to the original numbers array.
This happens because numbers and result are two different array objects.
Important: flat() Creates a Shallow Copy
Although flat() creates a new array, it does not perform a deep copy of all elements.
The method creates a shallow copy, meaning that nested objects and other reference-type elements are not cloned. Instead, their references are preserved.
For example:
const users = [
{ name: "John", age: 25 },
[{ name: "Alice", age: 30 }]
];
const result = users.flat();
console.log(result);
Output:
[
{ name: "John", age: 25 },
{ name: "Alice", age: 30 }
]
The new array contains the same object references that were present in the original array.
You can verify this by modifying an object through the flattened array:
const users = [
{ name: "John", age: 25 },
[{ name: "Alice", age: 30 }]
];
const result = users.flat();
// Modify an object through the new array
result[0].age = 35;
console.log("Original:", users[0].age);
console.log("Result:", result[0].age);
Output:
Original: 35
Result: 35
Notice that changing the age property through result also affects the corresponding object in users.
This happens because both arrays reference the same object. The array structure is copied, but the objects themselves are not duplicated.