zip

Description

Merges together the values of each of the array tables in tab with the same index. Useful when you have separate data sources that are coordinated through matching indexes.

Parameters

tab

Array table that includes sub-arrays. The sub-arrays should have the same size.

Return Values

res

An array table with new consolidated sub-arrays.

Code

--ZFUNC-zip-v1
local function zip( tab )

   function pluck( t, key )
      local res = {}
      for i, v in ipairs( t ) do table.insert( res, v[ key ] ) end
      return res
   end

   function max( t )
      local res = 0
      for i, v in ipairs( t ) do if #v > res then res = # v end end
      return res
   end

   local res = {}

   local length = max( tab )

   for i = 1, length do
      table.insert( res, pluck( tab, i ) )
   end

  return res
end

return zip

Examples

local t = require( "taptest" )
local same = require( "same" )
local zip = require( "zip" )

-- should work like the zip function from underscore.js
local res = zip{
   { "moe", "larry", "curly" },
   { 30, 40, 50 },
   { true, false, false }
}

t( #res, 3 )

t( same( res[ 1 ], { "moe", 30, true } ), true )
t( same( res[ 2 ], { "larry", 40, false } ), true )
t( same( res[ 3 ], { "curly", 50, false } ), true )

t()

Inspired by