-1

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] 

2 Answers2

2

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));
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

Make it recursive!

result = [];

function covert(array) {
for (var b in array) {
    if (typeof b === number) {
        result.push(b)
    } else {
        convert(b)
    }
}

}

adgon92
  • 219
  • 1
  • 7