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( "taptest" )
local flatten = require( "flatten" )

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

t( #res, 4 )

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

t()

Inspired by