The problem is how you are passing the processing of array, if the value is an array then you are keep calling it causing an infinite loop
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push.apply(flat, flatten.apply(this, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
Demo: Fiddle
Here's a more modern version:
function flatten(items) {
const flat = [];
items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});
return flat;
}
Answer from Arun P Johny on Stack Overflow Top answer 1 of 16
41
The problem is how you are passing the processing of array, if the value is an array then you are keep calling it causing an infinite loop
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push.apply(flat, flatten.apply(this, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
Demo: Fiddle
Here's a more modern version:
function flatten(items) {
const flat = [];
items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});
return flat;
}
2 of 16
31
The clean way to flatten an Array in 2019 with ES6 is flat()
Short Answer:
array.flat(Infinity)
Detailed Answer:
const array = [1, 1, [2, 2], [[3, [4], 3], 2]]
// All layers
array.flat(Infinity) // [1, 1, 2, 2, 3, 4, 3, 2]
// Varying depths
array.flat() // [1, 1, 2, 2, Array(3), 2]
array.flat(2) // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat().flat() // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat(3) // [1, 1, 2, 2, 3, 4, 3, 2]
array.flat().flat().flat() // [1, 1, 2, 2, 3, 4, 3, 2]
Mozilla Docs
Can I Use - 96% Oct '23
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 of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Videos
05:59
Flatten an Array with Recursion in Javascript - YouTube
10:05
Frontend Interview Question | How to Flatten Array of Array ? | ...
10:35
Flatten Nested Arrays with Recursion in JavaScript - YouTube
09:51
Flatten an Array with Recursion (JavaScript) - YouTube
06:03
JavaScript Flatten Nested Arrays with Recursion - YouTube
18:32
My First Take Home Interview Exercise: Flattening Nested Arrays ...
freeCodeCamp
freecodecamp.org › news › flatten-array-recursion
How to Flatten an Array in JavaScript Using Recursion
August 18, 2022 - If you carefully observe the above code, line 6 print1ToNo(currentValue + 1) is calling the same function with a new value (whatever the currentValue was, plus 1, i.e currentValue + 1). And it keeps doing it, until the currentValue goes past N, because that's when we told it to return. Now, this is what recursion means. Now, let's get back to our main problem – we need to flatten an Array.
GitHub
github.com › bradtraversy › traversy-js-challenges › blob › main › 04-recursion › 09-flatten-array › readme.md
traversy-js-challenges/04-recursion/09-flatten-array/readme.md at main · bradtraversy/traversy-js-challenges
As the loop iterates through each element of the input array arr, the recursion eventually reaches the point where there are no more elements left to process. When the input array arr is empty, the loop will not execute, and the function will ...
Author bradtraversy
Medium
medium.com › @me.sonu300 › flatten-array-using-recursion-functions-in-javascript-e033e5114e21
Flatten array using recursion functions in JavaScript? | by Sonu Kumar | Medium
June 2, 2024 - //flatten below given array let arr = [1,44, [2, [3,9], 67], 9]; //using recurssion function recur(a) { let newArr = []; for (let i =0 ; i < a.length; i++) { const element = a[i]; if (Array.isArray(element)) { newArr.push(...recur(element)) } else { newArr.push(element) } } return newArr; } console.log(recur(arr)) output: [1,44,2,3,9, 67, 9] //we can also write the same code using foreach: function flattenArray(items) { const flat = []; items.forEach(item => { if (Array.isArray(item)) { flat.push(...flatten(item)); } else { flat.push(item); } }); return flat; } console.log(flattenArray(arr)) output: [1,44,2,3,9, 67, 9]
TutorialsPoint
tutorialspoint.com › array-flattening-using-loops-and-recursion-in-javascript
Array flattening using loops and recursion in JavaScript
October 20, 2020 - ... const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]]; const flatten = function(){ let res = []; for(let i = 0; i < this.length; i++){ if(Array.isArray(this[i])){ res.push(...this[i].flatten()); }else{ res.push(this[i]); }; }; return res; }; Array.prototype.flatten = flatten; ...
Medium
medium.com › @conboys111 › flattening-arrays-in-javascript-recursion-vs-iterative-approaches-7164c2b5d165
Flattening Arrays in JavaScript: Recursion vs Iterative Approaches | by myHotTake | Medium
January 2, 2025 - function recursiveFlatten(arr) { return arr.reduce((flat, item) => { return flat.concat(Array.isArray(item) ? recursiveFlatten(item) : item); }, []); } console.log(recursiveFlatten(nested)); // Output: [1, 2, 3, 4, 5, 6] It works, but the problem is deep nesting. With arrays that are too deeply nested (think thousands of levels), the JavaScript call stack would overflow, leading to an error.
Medium
mccarthydanielle.medium.com › what-happens-when-you-flatten-an-array-using-recursion-da2954deece9
What happens when you flatten an array using recursion. | by Danielle McCarthy | Medium
December 17, 2018 - The result of this recursive call will eventually be pushed to our first function call’s result array. ... This is what the current call stack looks like. Current call stack. This is what the second function call looks like. ... Again, let’s think of this as an entirely new function call. We are invoking flattenArray with [‘ho’]. We know that this is the second element of our original array but for now let’s just focus on this function call.
Dtang
dtang.dev › 2019-04-05-learning-recursion-in-javascript-part-3
Learning Recursion in JavaScript Part 3 - Flattening Arrays | David Tang
April 5, 2019 - If those values are equal, we stop the recursion. Otherwise, we keep going. If a depth argument isn't passed into flat(), depth will be undefined. Thus, currentDepth, which starts off at 0, will never equal undefined, and our function will flatten the array for however deep it is.
ACM
helloacm.com › home › javascript › how to unroll/flatten array recursively using javascript?
How to Unroll/Flatten Array Recursively using Javascript? | Algorithms, Blockchain and Cloud
November 26, 2018 - // https://helloacm.com/how-to-unrollflatten-array-recursively-using-javascript/ function unrollArray(x) { let result = []; let func = function(arr) { if (Array.isArray(arr)) { let len = arr.length; for (let i = 0; i < arr.length; ++ i) { func(arr[i]); // do this recursively } } else { result.push(arr); // put the single element to result } } func(x); return result; }