Skip to content Skip to sidebar Skip to footer

Javascript: Flatten Multidimensional Array In Place Using Recursion

I have the following code that flattens a multidimensional array var x = [[[2, 3], 4], 5, [6, 7]]; function flatten(arr) { for (var i = 0; i < arr.length; i++) { if (arr

Solution 1:

Do the recursive flattening from the inside out. First call the flatten function on the array that you find, then move the contents of that (now flat) array into the parent array. Loop backwards through the array so that you don't have to adjust the loop variable for the items that are inserted.

As you know that the arrays that you insert are flat, you can use the splice method to replace an array with its items.

It works like this:

startwith[[[2, 3], 4], 5, [6, 7]]

flatten[6,7] (which is already flat) andinsert:
[[[2, 3], 4], 5, 6, 7]

flatten[[2, 3], 4] recursivelycallsflatten[2,3]andinsertsinthatarray:
[[2, 3, 4], 5, 6, 7]
thenitinserts[2, 3, 4]:
[2, 3, 4, 5, 6, 7]

Code:

functionflatten(arr) {
  for (var i = arr.length - 1; i >= 0; i--) {
    if (arr[i].constructor === Array) {
      flatten(arr[i]);
      Array.prototype.splice.apply(arr, [i, 1].concat(arr[i]));
    }
  }
}

var x = [[[2, 3], 4], 5, [6, 7]];

flatten(x);

// Show result in snippetdocument.write(JSON.stringify(x));

Post a Comment for "Javascript: Flatten Multidimensional Array In Place Using Recursion"