user606521
user606521

Reputation: 15424

How to remove all elements in array A from array B?

local a = {1, 2, 3}
local b = {1, 2, 3, 4, 5, 6}
-- I need b - a = {4, 5, 6}

I want to remove all elements from array b that are also present in array a. Looking for FASTEST solution.

Upvotes: 1

Views: 169

Answers (3)

Thomas Thomsen
Thomas Thomsen

Reputation: 86

This code copies the duplicate keys over to array c

local a = {1, 2, 3}
local b = {1, 2, 3, 4,5 ,6}
local c = {}

for k,v in ipairs(b) do
    local foundkey = false
    for _k,_v in ipairs(a) do
        if _v == v then 
            foundkey = true 
        end
    end
    if foundkey then 
        table.insert(c,v)
    end
end

Or

local a = {1, 2, 3}
local b = {1, 2, 3, 4, 5, 6}

for k,v in ipairs(b) do
    local key = 0
    for _k,_v in ipairs(a) do
        if _v == v then 
            key = _k
        end
    end
    if key ~= 0 then 
        table.remove(a,key )
    end
end

-- Outputs a = {7}

or

local a = {1, 2, 3}
local b = {1, 2, 3, 4, 5, 6}
local c = {}

for k,v in ipairs(b) do
    local foundkey = 0
    for _k,_v in ipairs(a) do
        if _v == v then 
            foundkey = _k
        end
    end
    if foundkey == 0 then 
        table.insert(c,v)
    end
end
a = c

-- Output a = {4, 5, 6}

Upvotes: 4

Etan Reisner
Etan Reisner

Reputation: 80921

Invert the smaller table into a hash and compare against it in a loop.

function invtab(t)
    local tab = {}
    for _, v in ipairs(t) do
        tab[v]=true
    end
    return tab
end

local a = {1, 2, 3}
local b = {1, 2, 3, 4, 5, 6}

local ainv = invtab(a)

-- To get a new table with just the missing elements.
local ntab = {}
for _, v in ipairs(b) do
    if not ainv[v] then
        ntab[#ntab + 1] = v
    end
end

-- To remove the elements in place.
for i = #b, 1, -1 do
    local v = b[i]
    if ainv[v] then
        table.remove(b, i)
    end
end

Upvotes: 4

Asif Mehmood
Asif Mehmood

Reputation: 473

you can use stack here. when just compare two indexes that are not same push into stack. stack.

Upvotes: 0

Related Questions