0

I was reading ruby's array flatten function and looking for similar function in Javascript and didn't found. So, I created it myself.

    Input: [[1,2,[3]],4]
    Output : [1,2,3,4]

If you want to use reduce/concate methods you will not get desired answer for multi dimensional array.

What can be the solution code you think ?!!!

  • @AndrewMorton Seemingly similar, but for nested multi-dimensional array that solution doesn't work. If you try that solution for this given array, you will see : [1,2,[3],4 ] . But I wanted [1,2,3,4] So, that didn't solved my problem and I wrote this solution – Abu Haider Siddiq Jun 12 '16 at 15:30
  • If all are numbers can do `newArr = arr.toString().split(',').map(Number)` – charlietfl Jun 12 '16 at 15:34
  • @dmsbilas The thread linked to is a long one, but [this answer](http://stackoverflow.com/a/15030117/13) is the one you need. – C. K. Young Jun 12 '16 at 15:45
  • Anyway, here's my solution that uses `splice` instead of `concat`, which may reduce memory usage: https://gist.github.com/cky/db218f63441e292fabf50d03c0f1b722 – C. K. Young Jun 12 '16 at 15:50
  • `var givenArr = [[1,2,[3]],4]; var arrString = JSON.stringify(givenArr); var stripped = arrString.replace(/\D/g,''); var newArr = stripped.split('').map(Number); ` – Jeremy Jackson Jun 12 '16 at 16:07
  • @JeremyJackson That assumes all the array elements are single-digit numbers. I believe the OP wants something more general than that. – C. K. Young Jun 12 '16 at 16:20

1 Answers1

0

So, here is the code I used to solve the solution.

    var givenArr = [[1,2,[3]],4];
    var outputArray = [];

    function typeOf(value) {
      var s = typeof value;
      if (s === 'object') {
        if (value) 
          {
            if (Object.prototype.toString.call(value) == '[object Array]') {
              s = 'array';
            }
          }else{
          s = 'null';
        }
      }
      return s;
    }

    function getElementFromArray(array)
    {
        if(array.length == 0 ) return;
        for(var i = 0; i< array.length; i++ )
        {
            if( typeOf(array[i]) === 'array' )
            {
                getElementFromArray(array[i]);
            }else{
                 outputArray.push(array[i]);
            }
        }
     }//end getElementFromArray

     getElementFromArray(givenArr);

     console.log(outputArray);

     //output [1,2,3,4]