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( "taptest" ) local pluck = require( "pluck" ) local same = require( "same" ) -- Array table test arr = { { "moe", "larry", "curly" }, { 30, 40, 50 }, { true, false, false } } res = pluck( arr, 1 ) t( #res, 3 ) t( same( res, { "moe", 30, true } ), true ) -- Dict table test dict = { { name = "moe", age = 30 }, { name = "larry", age = 40 }, { name = "curly", age = 60 } } res = pluck( dict, "name" ) t( #res, 3 ) t( same( res, { "moe", "larry", "curly" } ), true ) t()