Module:Util/tables/filter: Difference between revisions

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search
mNo edit summary
mNo edit summary
 
Line 5: Line 5:
local results = {}
local results = {}
for i, v in ipairs(tbl) do
for i, v in ipairs(tbl) do
if predicateFn(v) then
if predicate(v) then
table.insert(results, v)
table.insert(results, v)
end
end

Latest revision as of 20:42, 19 May 2024

filter(array, iteratee)

Returns

  • Iterates over array elements in array, returning an array of all elements iteratee returns truthy for.

Examples

#InputOutputResult
1
local games = {"TLoZ", "TAoL", "ALttP"}
return util.tables.filter(games, util.strings._startsWith("T"))
{"TLoZ", "TAoL"}
property iteratee shorthand
2
filter(
  {
    {
      canon = true,
      game = "The Wind Waker",
    },
    {
      canon = true,
      game = "Twilight Princess",
    },
    {
      canon = false,
      game = "Tingle's Rosy Rupeeland",
    },
  },
  "canon"
)
{
  {
    canon = true,
    game = "The Wind Waker",
  },
  {
    canon = true,
    game = "Twilight Princess",
  },
}
isMatch iteratee shorthand
3
filter(
  {
    {
      type = "main",
      game = "The Wind Waker",
    },
    {
      type = "main",
      game = "Twilight Princess",
    },
    {
      type = "spinoff",
      game = "Tingle's Rosy Rupeeland",
    },
  },
  { type = "main" }
)
{
  {
    type = "main",
    game = "The Wind Waker",
  },
  {
    type = "main",
    game = "Twilight Princess",
  },
}

local iteratee = require("Module:Util/tables/iteratee")

local function filter(tbl, predicate)
	predicate = iteratee(predicate)
	local results = {}
	for i, v in ipairs(tbl) do
		if predicate(v) then
			table.insert(results, v)
		end
	end
	return results
end

return filter