Module:Util/tables/groupBy

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search

groupBy(array, iteratee)

Returns

  • A table composed of keys generated from the results of running each element of array thru iteratee. The order of grouped values is determined by the order they occur in array. The corresponding value of each key is an array of elements responsible for generating the key. If a nil key is generated for a given value, that value will be absent from the resulting table.

Examples

#InputOutputResult
1
return Util.tables.groupBy({6.1, 4.2, 6.3}, math.floor)
{
  [6] = {6.1, 6.3},
  [4] = {4.2},
}
property iteratee shorthand
2
groupBy(
  {
    {
      term = "Hero of Time",
      game = "OoT",
      page = "Link",
    },
    {
      term = "Hero of Winds",
      game = "TWW",
      page = "Link",
    },
    {
      term = "Zelda",
      game = "SS",
      page = "Princess Zelda",
    },
    { someOtherData = "foo" },
  },
  "page"
)
{
  ["Princess Zelda"] = {
    {
      term = "Zelda",
      game = "SS",
      page = "Princess Zelda",
    },
  },
  Link = {
    {
      term = "Hero of Time",
      game = "OoT",
      page = "Link",
    },
    {
      term = "Hero of Winds",
      game = "TWW",
      page = "Link",
    },
  },
}

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

local function groupBy(tbl, func)
	func = iteratee(func)
	local res = {}
	for i, v in ipairs(tbl) do
		local k = func(v)
		if k then
			res[k] = res[k] or {}
			table.insert(res[k], v)
		end
	end
	return res
end

return groupBy