Pluto icon indicating copy to clipboard operation
Pluto copied to clipboard

table.countvalues

Open Sainan opened this issue 2 years ago • 4 comments

function table.countvalues(t)
    local counts = {}
    for t as elm do
        counts[elm] = (counts[elm] ?? 0) + 1
    end
    return counts
end

Sainan avatar Dec 15 '23 21:12 Sainan

Could consider table.values() instead that returns an array of values

well-in-that-case avatar Dec 15 '23 23:12 well-in-that-case

Wdym?

Sainan avatar Dec 16 '23 01:12 Sainan

local assert = require("assert")
local t = { a = 1, b = 2, c = 3 }
assert.equals({ 1, 2, 3 }, t:values())

Then you could query for length if you needed.

well-in-that-case avatar Dec 16 '23 03:12 well-in-that-case

How does that solve this? image

Sainan avatar Dec 16 '23 03:12 Sainan