flatten

function flatten( arr [, shallow] ) --> flatarr

Description

Flattens nested arrays in array table. The nesting can be to any depth. If you pass shallow, the array will only be flattened a single level.

Parameters

arr

The array table that should be flatten.

shallow

Defines how deep the the sub array should be flatten. If you pass shallow, the array table will only be flattened a single level. If shallow is omitted flattes the function every nested array.

Return Values

flatarr

The flattened array table.

Code

--ZFUNC-flatten-v1
local function flatten( arr, shallow ) --> flatarr
   local flatarr = {}
   for _, v in ipairs( arr ) do
      if shallow or type( v ) ~= 'table' then
         table.insert( flatarr, v )
      else
         for _, sub_v in ipairs( flatten( v ) ) do
            table.insert( flatarr, sub_v )
         end
      end
   end
   return flatarr
end

return flatten

Examples

local t = require( "tapered" )
local flatten = require( "flatten" )

local res = flatten{ "a", { "b" }, { "c", { { "d" } } } }

t.is( 4, #res )

t.is( "a", res[ 1 ] )
t.is( "b", res[ 2 ] )
t.is( "c", res[ 3 ] )
t.is( "d", res[ 4 ] )

t.done()

Inspired by