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=王五