- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Array flat
JavaScript Arrays
JavaScript Array flat
JavaScript
flatturns a nested array into a shallower one.
By default it only removes one level of nesting.
flatMap does a map and a single flat in one step.
Example
Example
javascript
const nested = [1, [2, 3], [4]];
console.log(nested.flat().join(","));The output is 1,2,3,4.
flat and flatMap
flat(depth) returns a new array with nested arrays pulled up.
The default depth is 1.
flatMap runs a callback and then flattens the result by one level.
Syntax
Syntax
javascript
array.flat(depth);
array.flatMap(callback);Both return a new array and leave the original alone.
Deeper Nesting
One call only removes one level unless you say otherwise.
Example
Example
javascript
const deep = [1, [2, [3, [4]]]];
console.log(deep.flat().length);
console.log(deep.flat(2).length);Each extra level of depth pulls up one more layer.
Flatten Everything
Infinity flattens however deep the nesting goes.
Example
Example
javascript
const deep = [1, [2, [3, [4]]]];
console.log(deep.flat(Infinity).join(","));The output is 1,2,3,4.
Removing Empty Slots
flat also drops holes in a sparse array.
Example
Example
javascript
const sparse = [1, , 3];
console.log(sparse.flat().length);The empty slot disappears, leaving two elements.
flatMap
This is useful when each element becomes several elements.
Example
Example
javascript
const sentences = ["a b", "c d"];
console.log(sentences.flatMap(s => s.split(" ")).join(","));Without flatMap you would get an array of arrays.
flatMap Only Goes One Level
If the callback returns deeper nesting, you still need flat.
Example
Example
javascript
const list = [1, 2];
console.log(list.flatMap(n => [n, [n * 10]]).length);The inner arrays are still there, because only one level was flattened.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript flat</title>
</head>
<body>
<h1>JavaScript flat</h1>
<p id="result"></p>
<script>
const groups = [["Ada", "Grace"], ["Alan"], ["Edsger"]];
const everyone = groups.flat();
document.getElementById("result").innerHTML = everyone.join(", ");
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try nesting deeper:
Wrap one group in another array and see that flat() alone is not enough.
Important Points
flatremoves one level of nesting by default.- Pass a depth to remove more levels.
flat(Infinity)flattens completely.flatalso removes empty slots.flatMapis amapfollowed by one level of flattening.
Conclusion
flat tidies nested arrays into a single list.
flatMap saves a step when each element expands into several.
Both return new arrays, so the original stays as it was.
