-1

I am trying to flatten a nested array contained in array variable. Everything looks fine in the code but still not working. Please help me what's wrong with my code. According to me this code should return a flatten array like [1,2,3,4].

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

function flatten(array){

        return array.map(function(currentElement){

            if(Array.isArray(currentElement)){
                return flatten(currentElement);
            }else{
                return currentElement;
            }
        });
}

console.log(flatten(array)); // [1,[2],[3,[[4]]]]

// expected result => [1,2,3,4]
Gopendra
  • 15
  • 1
  • 7

2 Answers2

1

Just use toString()

var array = [1,[2],[3,[[4]]]];
array = array.toString();
array = array.split(',');
console.log(array);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

You can use a combo of reduce and concat for this purpose, since flat is not implemented yet in the majority of the browsers.

const flatten = array => 
  array.reduce((r, v) => r.concat(Array.isArray(v) ? flatten(v) : v), []);


console.log(flatten([1,[2],[3,[[4]]]])) // [1, 2, 3, 4]
ZER0
  • 24,846
  • 5
  • 51
  • 54