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( "tapered" )
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.is( 3, #res )

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

t.done()

Inspired by