lua table去重(table.unique)拓展,根据表元素去重

table.unique 原代码:

function table.unique(t, bArray)
    local check = {}
    local n = {}
    local idx = 1
    for k, v in pairs(t) do
        if not check[v] then
            if bArray then
                n[idx] = v
                idx = idx + 1
            else
                n[k] = v
            end
            check[v] = true
        end
    end
    return n
end

 

如果我们的table是一个嵌套的table,例如一个学生清单,有id和name,想根据id进行去重,以上代码就无法满足。

于是在原代码基础上进行拓展,引入去重的主key就可以解决,同时原代码的功能还在。

function table.unique(t, bArray, mainKey)
    local check = {}
    local n = {}
    local idx = 1
    for k, v in pairs(t) do
        local judgeKey = v
        if mainKey then
            judgeKey = v[mainKey] or v
        end
        if not check[judgeKey] then
            if bArray then
                n[idx] = v
                idx = idx + 1
            else
                n[k] = v
            end
            check[judgeKey] = true
        end
    end
    return n
end

用法:例如 

local studentTable = {

[1] = {id = 1, name = "张三"},

[2] = {id = 2, name = "李四"},

[3] = {id = 1, name = "张三"},

[3] = {id = 3, name = "王五"},

}

print("before table.unique")
for k,v in pairs(studentTable) do
    print( "id=" .. v.id .. ",name=" .. v.name )
end

studentTable = table.unique(studentTable ,true, "id")

print("\nafter table.unique")
for k,v in pairs(studentTable) do
    print( "id=" .. v.id .. ",name=" .. v.name )
end

 

运行结果:

before table.unique
id=2,name=李四
id=1,name=张三
id=1,name=张三
id=3,name=王五

after table.unique
id=2,name=李四
id=1,name=张三
id=3,name=王五
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值