Javascript recursive array flattening

javascript recursive function array
create a nested array recursively in javascript
javascript flatten(array of objects)
flatten array javascript
write a program to flatten a given n dimensional array
flatten json javascript
flatten object javascript
remove nested array javascript

I'm exercising and trying to write a recursive array flattening function. The code goes here:

function flatten() {
    var flat = [];
    for (var i = 0; i < arguments.length; i++) {
        if (arguments[i] instanceof Array) {
            flat.push(flatten(arguments[i]));
        }
        flat.push(arguments[i]);
    }
    return flat;
}

The problem is that if I pass there an array or nested arrays I get the "maximum call stack size exceeded" error. What am I doing wrong?


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;
}

Javascript recursive array flattening, When I first started learning about recursion, I didn't fully understand what JavaScript was doing in the background. The purpose of this article is  The flat () method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.


[...arr.toString().split(",")]

Use the toString() method of the Object. Use a spread operator (...) to make an array of string and split it by ",".

Example:

let arr =[["1","2"],[[[3]]]]; // output : ["1", "2", "3"]

What happens when you flatten an array using recursion., For this third post in this series on recursion, we're going to look at writing a function to flatten a nested array with an arbitrary depth. For example,  Flatten an array means give an array that consist of elements and subarrays(that also might contain several layers of subarrays) we combine all the elements into one array.


A Haskellesque approach...

function flatArray([x,...xs]){
  return x !== undefined ? [...Array.isArray(x) ? flatArray(x) : [x],...flatArray(xs)]
                         : [];
}

var na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
    fa = flatArray(na);
console.log(fa);

Learning Recursion in JavaScript Part 3 - Flattening Arrays, The classical recursive way is based on a function calling itself if the i element in the array that we are looping through is also an array. This  Flattening arrays in JavaScript. Flattening arrays may not be an everyday need but, it is still an important need enough to be part of most utility libraries in JavaScript. If you have looked at this very simple problem before you have probably noticed that most of the time we only see one kind of implementation for it, the recursive way.


If the item is array, we simply add all the remaining items to this array

function flatten(array, result) {
  if (array.length === 0) {
    return result
  }
  var head = array[0]
  var rest = array.slice(1)
  if (Array.isArray(head)) {
    return flatten(head.concat(rest), result)
  }
  result.push(head)
  return flatten(rest, result)
}

console.log(flatten([], []))
console.log(flatten([1], []))
console.log(flatten([1,2,3], []))
console.log(flatten([1,2,[3,4]], []))
console.log(flatten([1,2,[3,[4,5,6]]], []))
console.log(flatten([[1,2,3],[4,5,6]], []))
console.log(flatten([[1,2,3],[[4,5],6,7]], []))
console.log(flatten([[1,2,3],[[4,5],6,[7,8,9]]], []))

Flattening arrays in JavaScript, A new array with the sub-array elements concatenated into it. non recursive flatten deep using a stack // note that depth control is  How to flatten an array in JavaScript In vanilla JavaScript, you can use the Array.concat () method to flatten a multi-dimensional array. This method works in all modern browsers, and IE6 and above. Here is an example:


Your code is missing an else statement and the recursive call is incorrect (you pass the same array over and over instead of passing its items).

Your function could be written like this:

function flatten() {
    // variable number of arguments, each argument could be:
    // - array
    //   array items are passed to flatten function as arguments and result is appended to flat array
    // - anything else
    //   pushed to the flat array as-is
    var flat = [],
        i;
    for (i = 0; i < arguments.length; i++) {
        if (arguments[i] instanceof Array) {
            flat = flat.concat(flatten.apply(null, arguments[i]));
        } else {
            flat.push(arguments[i]);
        }
    }
    return flat;
}

// flatten([[[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]], [[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]]]);
//            [0, 1, 2,   0, 1, 2,     0, 1, 2,   0, 1, 2,       0, 1, 2,   0, 1, 2,     0, 1, 2,   0, 1, 2]

Array.prototype.flat(), How to Unroll/Flatten Array Recursively using Javascript? Please note that we define the local function that is only visible inside the function  So before we get into writing this function, it is worth noting that as of ES2019, there is a new Array.prototype.flat() method for flattening arrays. I wrote a post about it called Flattening Arrays in JavaScript with flat() and flatMap() if you’d like to learn more about it.


How to Unroll/Flatten Array Recursively using Javascript , If its an integer, we just need to add it to our flattened array. ourselves in Javascript using recursion without having it blow up the call stack. and our target is to unroll (or flatten) it so the output array becomes: 1 var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; Our approach is to go through each element of array (if it is array) recursively and push to a local/scoped array.


JavaScript Flatten Nested Arrays with Recursion, However, flattening arrays has been easy in JavaScript every since ECMAScript 6 (2015) introduced generators. Because generators can yield values in any order, not just linearly, it’s possible to use a recursive generator to easily flatten an array.


Flatten an Array with Recursion (JavaScript), This is called a recursive step: we transform the task into a simpler action (multiplication by x) and a simpler call of the same task (pow with lower n). Next steps simplify it further and further until n reaches 1. We can also say that pow recursively calls itself till n == 1.