-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() Commented Jun 4, 2018 at 10:48
  • jsfiddle.net/8ved8xwt 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);

Sign up to request clarification or add additional context in comments.

3 Comments

nice solution... :)
@AnkurShah welcome
But I need to flatten this array using Recursion. is my code wrong?
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 Comments

thanks a lot. it was helpful.
but still could not find why my code is not working.
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.