Perfect use case for recursion, which could handle even deeper structure:

function flatten(ary) {
    var ret = [];
    for(var i = 0; i < ary.length; i++) {
        if(Array.isArray(ary[i])) {
            ret = ret.concat(flatten(ary[i]));
        } else {
            ret.push(ary[i]);
        }
    }
    return ret;
}

flatten([[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]]) // [0, 1, 2, 3, 4, 5]

Alternatively, as an Array method:

Array.prototype.flatten = function() {
    var ret = [];
    for(var i = 0; i < this.length; i++) {
        if(Array.isArray(this[i])) {
            ret = ret.concat(this[i].flatten());
        } else {
            ret.push(this[i]);
        }
    }
    return ret;
};

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flatten() // [0, 1, 2, 3, 4, 5]

EDIT #1: Well, think it a little bit functional way (except for the named recursion which should be using Y-combinator for pure functional :D).

function flatten(ary) {
  return ary.reduce(function(a, b) {
    if (Array.isArray(b)) {
      return a.concat(flatten(b))
    }
    return a.concat(b)
  }, [])
}

Let's adopt some ES6 syntax which makes it even shorter, in one line.

const flatten = (ary) => ary.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])

But remember, this one cannot be applied as an array method, because arrow functions don't have theirs own this.


EDIT #2: With the latest Array.prototype.flat proposal this is super easy. The array method accepts an optional parameter depth, which specifies how deep a nested array structure should be flattened (default to 1).

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat()  // [[[[0]], [1]], [[[2], [3]]], [[4], [5]]]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(2) // [[[0]], [1], [[2], [3]], [4], [5]]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(3) // [[0], 1, [2], [3], 4, 5]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(4) // [0, 1, 2, 3, 4, 5]

So to flatten an array of arbitrary depth, just call flat method with Infinity.

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(Infinity) // [0, 1, 2, 3, 4, 5]
Answer from Leo on Stack Overflow
Top answer
1 of 16
76

Perfect use case for recursion, which could handle even deeper structure:

function flatten(ary) {
    var ret = [];
    for(var i = 0; i < ary.length; i++) {
        if(Array.isArray(ary[i])) {
            ret = ret.concat(flatten(ary[i]));
        } else {
            ret.push(ary[i]);
        }
    }
    return ret;
}

flatten([[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]]) // [0, 1, 2, 3, 4, 5]

Alternatively, as an Array method:

Array.prototype.flatten = function() {
    var ret = [];
    for(var i = 0; i < this.length; i++) {
        if(Array.isArray(this[i])) {
            ret = ret.concat(this[i].flatten());
        } else {
            ret.push(this[i]);
        }
    }
    return ret;
};

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flatten() // [0, 1, 2, 3, 4, 5]

EDIT #1: Well, think it a little bit functional way (except for the named recursion which should be using Y-combinator for pure functional :D).

function flatten(ary) {
  return ary.reduce(function(a, b) {
    if (Array.isArray(b)) {
      return a.concat(flatten(b))
    }
    return a.concat(b)
  }, [])
}

Let's adopt some ES6 syntax which makes it even shorter, in one line.

const flatten = (ary) => ary.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])

But remember, this one cannot be applied as an array method, because arrow functions don't have theirs own this.


EDIT #2: With the latest Array.prototype.flat proposal this is super easy. The array method accepts an optional parameter depth, which specifies how deep a nested array structure should be flattened (default to 1).

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat()  // [[[[0]], [1]], [[[2], [3]]], [[4], [5]]]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(2) // [[[0]], [1], [[2], [3]], [4], [5]]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(3) // [[0], 1, [2], [3], 4, 5]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(4) // [0, 1, 2, 3, 4, 5]

So to flatten an array of arbitrary depth, just call flat method with Infinity.

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(Infinity) // [0, 1, 2, 3, 4, 5]
2 of 16
53

ES6-style with recursion:

Redacted

June 2018 Update:

There is now an ES proposal for an Array.prototype.flat method. It is currently at stage 3, meaning it's likely to be implemented by browsers soon(ish) and make it into the spec in its current form. There are probably some polyfills floating around.

Example:

const nested = [[[0], [1]], [[2], [3]], [[4], [5]]];
const flattened = nested.flat(2);  // Need to specify depth if > 1

June 2019 Update:

Array.prototype.flat was officially added to the language in the ES2019 spec.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › flat
Array.prototype.flat() - JavaScript - MDN Web Docs
The flat() method removes empty slots if the array being flattened is sparse. For example, if depth is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves.
Discussions

Best Ways to Deep Flatten Arrays in JavaScript?
What's wrong with just arr.flat(Infinity)? More on reddit.com
🌐 r/learnjavascript
11
0
January 2, 2025
Flatten a nested array
Hey guys, I have a question regarding one of the challenges in the JavaScript course. I should flatten a nested array without using .flat(). I knew that I would need to use some kind of recursive function but in the end I could not come up with something that would be working properly. More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
July 12, 2021
How to make a flatten list function recursive? I made it iterative...
It doesn't actually work. Do you know about doctest? You can put this at the end of your file to run the code in your docstring: import doctest doctest.testmod() You'll see that it has a problem with the deeply nested list. Basically it's only flattening one level down, because you're not using recursion. The fix is simple though. When you find an element which is a list, you need to recursively flatten that element before you concatenate it to the list you're going to return. I.e. lst1 = lst[0:i] + lst[i] needs to be lst1 = lst[0:i] + flatten(lst[i]) Oh, but actually this still doesn't work. It turns [[1, [1, 1]], 1, [1, 1]] to [[1, [1, 1]], 1, 1, 1]---seems it somehow failed to flatten the first list element. Actually, what is happening is that you are concatenating to lst (the original, un-flattened list) rather than lst1 (the new list you're building). You could make yourself less likely to make that kind of error by giving your variables more helpful names, like, say, "old_list" for lst and "new_list" for lst1. You'd have probably noticed the problem if what you had written was new_list = old_list[0:i] + old_list[i] EDIT: Actually there is still a problem even after you make both these fixes :) It gives you a flat list but not the right flat list. I'll leave that for you to solve. Hint: when you flatten a list, its length might increase. More on reddit.com
🌐 r/learnpython
4
1
September 23, 2022
How to flatten a deep nested Array in JS

While this method works, it's... not that great. It uses a ton of memory creating new arrays with recursive concat calls. You can do it in place and iteratively on a single array, which should be much faster and less costly:

var nested = [3, [1, 'hey', [2, 'you', [2, 5]]], 1, [9, [{}, [2, true]]]];

var flat = [].concat(nested);

for(var i = 0; i < flat.length; i++) {
    if(Array.isArray(flat[i])) {
        flat.splice(i, 1, ...flat[i--]);  
    }
}

console.log(flat);
More on reddit.com
🌐 r/javascript
9
4
August 12, 2016
🌐
DEV Community
dev.to › emmaadesile › how-to-flaten-a-nested-array-4pa2
How to flatten a nested array in Javascript - DEV Community
August 22, 2020 - #javascript · Today, I'll show you two ways to flaten a nested array regardless of how deeply nested it is. function flatten(arr) { return arr.flat(Infinity) } const numArr = [1, [2, [3], 4, [5, 6, [7]]]]; flatten(numArr) // [1, 2, 3, 4, 5, 6, 7] function flatten(arr) { const newArr = arr.reduce((acc, item) => { if (Array.isArray(item)) { acc = acc.concat(flatten(item)); } else { acc.push(item); } return acc; }, []); return newArr; } const numArr = [1, [2, [3], 4, [5, 6, [7]]]]; flatten(numArr) // [1, 2, 3, 4, 5, 6, 7] Subscribe ·
🌐
CodeBurst
codeburst.io › how-to-flatten-a-nested-javascript-array-628e01b85512
How to Flatten a Nested Javascript Array | by Cynthia Okoliezeh | codeburst
August 12, 2020 - The flat()method has an optional argument known as depth (the number of levels to flatten the array) and returns a new array - flattened version of the original array, removing any array hole (empty slot(s) in the array).
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Array › flat
JavaScript Array flat() - Flatten Nested Arrays | Vultr Docs
November 28, 2024 - The flat() method in JavaScript ... depth. Define an array that contains nested arrays. Use the flat() method without specifying a depth to flatten the array one level deep....
🌐
CoreUI
coreui.io › answers › how-to-flatten-a-nested-array-in-javascript
How to flatten a nested array in JavaScript · CoreUI
September 20, 2025 - Use the flat() method to convert nested arrays into a single-level array with modern ES2019 syntax in JavaScript.
🌐
Medium
medium.com › swlh › how-to-flatten-an-array-in-javascript-6b3fef075655
How to Flatten an Array in JavaScript | by Devin Michael Gray | The Startup | Medium
December 16, 2020 - Because it is a generator, instead of waiting for our recursive function to finish and return all of our values at once, our recursive function will instead yield each element of the nested array as it is encountered. Since generator functions return iterators, we use the spread syntax to iterate over our old array and return a new one. function* flatten(array, depth) { if(depth === undefined) { depth = 1; } for(const item of array) { if(Array.isArray(item) && depth > 0) { yield* flatten(item, depth - 1); } else { yield item; } } }const arr = [1, 2, [3, 4, [5, 6]]]; const flattened = [...flatten(arr, Infinity)]; // [1, 2, 3, 4, 5, 6]
Find elsewhere
🌐
W3Schools
w3schools.com › jsref › jsref_array_flat.asp
JavaScript Array flat() Method
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
🌐
Flexiple
flexiple.com › javascript › flatten-array-javascript
JavaScript: Flatten an array using different methods - Flexiple
The flat() method is used to create a new array with all sub-array elements concatenated into it recursively up to the specified depth. The depth parameter is optional and when no depth is specified, a depth of 1 is considered by default · ...
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-array-exercise-21.php
JavaScript array: Flatten a nested array - w3resource
July 12, 2025 - // Function to flatten a nested array const flatten = (a, shallow, r = []) => { // If shallow is true, use concat and spread syntax to flatten the array if (shallow) { return [...r, ...[].concat(...a)]; } // Iterate through each element in the ...
🌐
ExplainThis
explainthis.io › en › swe › flattening-deeply-nested-array
[Medium] LeetCode JS 30 - 2625. Flatten Deeply Nested Array|ExplainThis
March 7, 2024 - Think of it like unwrapping nested boxes -- to unwrap the innermost box, you must first unwrap all the larger boxes containing it. First, create a flat function that takes arr and n . In the flat , createe an empty array named result to hold ...
🌐
Reddit
reddit.com › r/learnjavascript › best ways to deep flatten arrays in javascript?
r/learnjavascript on Reddit: Best Ways to Deep Flatten Arrays in JavaScript?
January 2, 2025 -

Flattening arrays with .flat() is simple, but handling deeply nested arrays can be tricky. What’s your go-to approach for deep flattening in JavaScript? I came across this interesting write-up with some techniques: Deep Flatten Arrays in JavaScript. https://www.interviewsvector.com/javascript/deep-flaten

Would love to hear your thoughts or see alternative methods!

🌐
4Geeks
4geeks.com › how-to › javascript-array-flatten
How to flatten an array in JavaScript?
July 16, 2025 - If you don't pass an argument to the flat() method it will only flatten the values of the first layer, to go deeper you need to specify the number of layers to flatten, for example, 5 but if you don't know how many layers you need to pass as ...
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.flat()
JavaScript Array flat()
November 7, 2024 - In practice, you’ll find the flat() method useful when working with nested arrays. Let’s take some examples of using the flat() method. The following example uses the flat() method to flatten an array of numbers: const numbers = [1, 2, [3, ...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Flatten a nested array - JavaScript - The freeCodeCamp Forum
July 12, 2021 - Hey guys, I have a question regarding one of the challenges in the JavaScript course. I should flatten a nested array without using .flat(). I knew that I would need to use some kind of recursive function but in the end…
🌐
DEV Community
dev.to › dillionmegida › arrayflat-for-flatting-nested-arrays-within-an-array-3d1o
Array.flat() - for flatting nested arrays within an array - DEV Community
September 8, 2022 - const array = [1, 2, [3, 4, [5, 6]]] const flattenedArr = [] // for 2 levels for (let i = 0; i < array.length; i++) { const item = array[i] if (!Array.isArray(item)) { // not an array flattenedArr.push(item) } else { // for the first level for (let j = 0; j < item.length; j++) { const item2 = item[j] if (!Array.isArray(item2)) { // not an array flattenedArr.push(item2) } else { // for the second level flattenedArr.push(...item2) } } } } console.log(flattenedArr) // [ 1, 2, 3, 4, 5, 6 ] Looping and looping, just to flatten an array.
🌐
Designcise
designcise.com › web › tutorial › how-to-flatten-a-multidimensional-array-in-javascript
How to Flatten a Deeply Nested JavaScript Array? - Designcise
May 8, 2021 - In ES6+, you can use the spread operator along with the Array.prototype.concat() method to flatten a deep nested array like so:
🌐
SamanthaMing
samanthaming.com › tidbits › 71-how-to-flatten-array-using-array-flat
Flatten Array using Array.flat() in JavaScript | SamanthaMing.com
Here is a ES6 solution. This only work for one level nested array. const oneLevelDeep = [[1, 2], [3]]; const flattened = [].concat(...oneLevelDeep); // [1, 2, 3,]
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.flat()
Array.prototype.flat() - JavaScript Tutorial
November 7, 2024 - Note that JavaScript also offers the flatMap() which is more efficient than calling the map() and flat() consecutively. Use the Array flat() method to flatten an array with the nested arrays.
🌐
YouTube
youtube.com › watch
How to Flatten an Array in JavaScript |Use flat(), Recursion & Other Methods to Handle Nested Arrays - YouTube
Working with nested arrays in JavaScript? In this beginner-friendly tutorial, you'll learn how to flatten an array in JavaScript using multiple methods like ...
Published   July 8, 2025