-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]
2
  • what about calling simply array.toString()
    – M14
    Commented Jun 4, 2018 at 10:48
  • jsfiddle.net/8ved8xwt
    – M14
    Commented Jun 4, 2018 at 10:49

2 Answers 2

1

Just use toString()

var array = [1,[2],[3,[[4]]]];
array = array.toString();
array = array.split(',');
console.log(array);

3
  • nice solution... :)
    – Ankur Shah
    Commented Jun 4, 2018 at 10:52
  • @AnkurShah welcome Commented Jun 4, 2018 at 10:53
  • But I need to flatten this array using Recursion. is my code wrong?
    – Gopendra
    Commented Jun 4, 2018 at 11:14
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]
3
  • thanks a lot. it was helpful.
    – Gopendra
    Commented Jun 4, 2018 at 11:28
  • but still could not find why my code is not working.
    – Gopendra
    Commented Jun 4, 2018 at 11:50
  • 1
    Because you don't use concat, that's the key method. And, you're using map, so you can't really flatten with map since it returns always an array (of array, in your case).
    – ZER0
    Commented Jun 4, 2018 at 12:41

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.