mattHunting10 mattHunting10 - 2 months ago 16
Javascript Question

Converting multi-nested array into one array

I want to convert this array, into one array as shown below. How can I accomplish this with a method that will work, regardless of the level of nesting in the array.

var array = [1, [2], [3, [[4]]]]
//Output = [1,2,3,4]

Answer

You can use recursive function for this.

var array = [1, [2], [3, [[4]]]];

function flatten(ar) {
  var result = [];

  ar.forEach(function(e) {
    if (Array.isArray(e)) {
      result = result.concat(flatten(e));
    } else {
      result.push(e);
    }
  })

  return result;
}

console.log(flatten(array));

Comments