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
However, its elements must be arrays if they are to be flattened. ... const arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ... const arr5 = [1, 2, , 4, 5]; console.log(arr5.flat()); // [1, 2, 4, 5] const array = [1, , 3, ["a", , "c"]]; console.log(array.flat()); // [ 1, 3, "a", "c" ] const array2 = [1, , 3, undefined, ["a", , ["d", , "e"]], null]; console.log(array2.flat()); // [ 1, 3, undefined, "a", ["d", empty, "e"], null ] console.log(array2.flat(2)); // [ 1, 3, undefined, "a", "d", "e", null ]
Discussions

Flatten a nested array without using the inbuilt flat() method (interview learning)
const flatten = (arr) => { const items = []; for (const x of arr) { if (Array.isArray(x)) { items.push(...flatten(x)); } else { items.push(x); } } return items; }; console.log(flatten([0, [1, 2, [33, 44]], [4, 5, 6, 7], [7, 8], 90])); More on reddit.com
🌐 r/learnjavascript
23
26
January 8, 2026
How to flatten this nested array
const result = array.map((_, i) => ({ name: array[0][i].name, age: array[1][i].age, job: array[2][i].job })) More on reddit.com
🌐 r/learnjavascript
17
2
July 20, 2022
Flattened an array without using array.flat
Tell us what’s happening: So I just getting frustrated. I use the flat works like charm. However the the test are to use an alternative. the code is suppose to check for an array and the flatten the array until there is just one level. Its not working. Ugh Your code so far function ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
September 29, 2020
Introducing a Method to Flatten Nested Arrays in Repository!
Ahh, I hate to break it to you, but Array.flat() is already a thing! There'a also Array.flatMap() if you simultaneously want to perform an operation on each item in that flattened array 👍 More on reddit.com
🌐 r/learnjavascript
4
0
July 8, 2023
🌐
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…
🌐
Reddit
reddit.com › r/learnjavascript › flatten a nested array without using the inbuilt flat() method (interview learning)
r/learnjavascript on Reddit: Flatten a nested array without using the inbuilt flat() method (interview learning)
January 8, 2026 -

In an interview, I was asked to flatten a nested array in JavaScript without using `flat()`.

Under pressure, I got stuck. Later, I realized it wasn’t that hard — I was just overthinking.

Here’s the recursive solution I wrote:

var array = [0, [1, 2, [33, 44]], [4, 5, 6, 7], [7, 8], 90];

var newArr = [];

function getFlatArray(array) {

for (let index = 0; index < array.length; index++) {

if (typeof array[index] === "number") {

newArr.push(array[index]);

} else {

getFlatArray(array[index]);

}

}

}

getFlatArray(array);

console.log(newArr);

(12) [0, 1*,* 2*,* 33*,* 44*,* 4*,* 5*,* 6*,* 7*,* 7*,* 8*,* 90*]*

🌐
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
🌐
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
🌐
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 ...
🌐
LeetCode
leetcode.com › problems › flatten-deeply-nested-array
Flatten Deeply Nested Array - LeetCode
Flatten Deeply Nested Array - Given a multi-dimensional array arr and a depth n, return a flattened version of that array. A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
🌐
Medium
claire-deboer.medium.com › how-to-flatten-an-array-in-javascript-5650ad6a7b8f
How to Flatten An Array in JavaScript | by Claire DeBoer | Medium
June 9, 2021 - The second two ways of handling flattening an array, using flat() and recursion, work on arrays nested at any level.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-merge-flatten-an-array-of-arrays-in-javascript
How to Merge/Flatten an array of arrays in JavaScript ? - GeeksforGeeks
July 23, 2025 - This process involves iterating through each nested array and appending its elements to a new array, resulting in a flattened structure. To Merge or flatten array we can use array.flat() method.
🌐
SamanthaMing
samanthaming.com › tidbits › 71-how-to-flatten-array-using-array-flat
Flatten Array using Array.flat() in JavaScript | SamanthaMing.com
Here's one for older browser and pre ES6. Again, this only works for one level nested array. const oneLevelDeep = [[1, 2], [3]]; const flattened = [].concat.apply([], oneLevelDeep); // [1, 2, 3,]
🌐
Codedamn
codedamn.com › news › javascript
Flattening an Array: Best Practices and Examples
July 4, 2023 - The flat() method is a built-in JavaScript method that flattens the input array into a new array. This method takes an optional depth parameter, which defines the depth level specifying how deep a nested array structure should be flattened.
🌐
Medium
akhtarvahid.medium.com › flatten-nested-array-recursively-array-flat-in-javascript-5350f9d6f08d
Flatten nested array recursively | Array.flat() in JavaScript | by Vahid Akhtar | Medium
June 30, 2023 - The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ... const hearts = ["💜",["💙"],["❤️‍🩹"]]; const flattened = heart.flat(); console.log(flattened); // ...
🌐
Xano Community
community.xano.com › ask-the-community › post › how-to-flatten-a-nested-array-of-objects-qLAA5ZqVkYHZndw
How to flatten a nested array of objects ?
October 8, 2024 - When using the flatten filter, my objects are broken down and I obtain [ "John", 20, "Lucy", 52, "Amina", 27 ] Any idea on how to make this work without having to use a for loop and merging the sub arrays one by one ?
🌐
Reddit
reddit.com › r/learnjavascript › how to flatten this nested array
r/learnjavascript on Reddit: How to flatten this nested array
July 20, 2022 -

Given this

[
    [{name: 'larry'}, {name: 'harry'}, {name: 'barry'}],
    [{age: 29}, {age: 26}, {age: 34}],
    [{job: 'spy'}, {job: 'seal'}, {job: 'hitman'}]
]

How do I get this?

[
    [{name: 'larry', age: 29, job: 'spy'}],
    [{name: 'harry', age: 26, job: 'seal'}],
    [{name: 'barry', age: 34, job: 'hitman'}]
]

I'm a bit stuck with this so some help would be great. I've tried combinations of reduce, flat, and map array functions but not getting the desired result.

Working with restructuring collections / data wrangling isn't my strong suit. Can anyone recommend some resources to help with this?

Thanks.

🌐
Flexiple
flexiple.com › javascript › flatten-array-javascript
JavaScript: Flatten an array using different methods - Flexiple
Here when we use the spread operator ... above, the Spread syntax (...) allows the concatenation operation to be performed on all the elements of the array and stores the result in an empty array thus giving us a flattened array...
🌐
TecHighness
techighness.com › home › java script flatten deeply nested array of objects into single level array
JavaScript Flatten Deeply Nested Array of Objects Into Single Level Array - TecHighness
December 26, 2022 - This method returns the member with no children, else returns a new array with the member, and the result of recursively called _.flatMapDeep. To delete children in the flattened array while keeping the original intact, we need to return a copy of the member using the spread operator in which children are removed.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-flatten-array-of-arrays-in-typescript
How to Flatten Array of Arrays in TypeScript ? - GeeksforGeeks
May 2, 2024 - This method uses the concat method along with apply to flatten the array. It essentially spreads the elements of the nested arrays into a new array.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Flattened an array without using array.flat - JavaScript - The freeCodeCamp Forum
September 29, 2020 - Tell us what’s happening: So I just getting frustrated. I use the flat works like charm. However the the test are to use an alternative. the code is suppose to check for an array and the flatten the array until there is just one level. Its not working. Ugh Your code so far function steamrollArray(arr) { var flattened = []; for (let i = 0; i