intersection

function intersection( a, b ) --> res

Description

Computes the values that are the intersection of both array tables. Each value in the result is present in both arrays.

Parameters

a

First array table.

b

Second array table.

Return Values

res

Values that are in both array tables.

Code

--ZFUNC-intersection-v1
local function intersection( a, b ) --> res
   --ZFUNC-indexof-v1
   local function indexof( arr, val, startidx )
      startidx = startidx or 1
      for i = startidx, #arr do
         local v = arr[ i ]
         if v == val then return i end
      end
      return nil
   end

   local res = {}
   for _, v in ipairs( a ) do
      if indexof( b, v ) then table.insert( res, v ) end
   end
   return res
end

return intersection

Examples

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

arr = intersection( { 1, 2, 3, 4, 5 }, { 2, 3, 7, 8 } )
t( same( arr, { 2, 3 } ), true )

t()