pluck

function pluck( tabs, key ) --> tab

Description

Extracts a array table with values from each sub-table with the same index/key.

Parameters

tabs

The table with sub-tables.

key

The index/key of each element that should be cliped.

Return Values

tab

An array table with the extracted values from the sub-tables.

Code

--ZFUNC-pluck-v1
local function pluck( tabs, key )
   local res = {}

   for i, v in ipairs( tabs ) do
      table.insert( res, v[ key ] )
   end

   return res
end

return pluck

Examples

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

-- Array table test
arr = { { "moe", "larry", "curly" }, { 30, 40, 50 }, { true, false, false } }
res = pluck( arr, 1 )

t.is( 3, #res )
t.same( { "moe", 30, true }, res )

-- Dict table test
dict = { { name = "moe", age = 30 },
         { name = "larry", age = 40 },
         { name = "curly", age = 60 } }
res = pluck( dict, "name" )

t.is( 3, #res )
t.same( { "moe", "larry", "curly" }, res )

t.done()

Inspired by