Search code examples
javascript

Javascript: flatten array of arrays


I have an array like this:

[
   [
      [
         {
            "text":"1"
         }
      ],
   ],
   [
      [
         {
            "text":"2"
         }
      ],
   ]
]

and I would like to remove the outer array so it looks like this:

[
   [
      {
         "text":"1"
      }
   ],
],
[
   [
      {
         "text":"2"
      }
   ],
]

I've tried using arr[0] to dereference but that loses the second element!

[
   [
      {
         "text":"1"
      }
   ]
]

What am I doing wrong?


Solution

  • You are defining an array with two members, each of which contains an object member:

    const arr = [
       [
          [
             {
                "text":"1"
             }
          ],
       ],
       [
          [
             {
                "text":"2"
             }
          ],
       ]
    ]
    

    When you do arr[0], you are getting the first of those arrays.

    What I think you want to do is "flatten" the array. You could either write your own flattening function, or use one from a library like Lodash.

    But if you did want to write your own code, you could simply write:

    const flatArr = [arr[0][0], arr[1][0]]
    

    ... but a flatten function from Lodash or elsewhere will handle many other cases of nested arrays.

    EDIT: As Sebastian Simon pointed out in the comments, another option is the new (and not yet in Edge or Internet Explorer) flat method. If you use Babel or a polyfill or something to support those browsers, you can just do:

    const flatArr = arr.flat(2);