Is there a conventional name for a sort of "multi-group-by" function?
I'm looking for something that can put one item into potentially multiple groups?
For example, given the following input:
[
{ name: "x", groups: ["a", "b"] },
{ name: "y", groups: ["a"] },
{ name: "z", groups: ["b"] }
]
It should produce the following output:
{
a: [
{ name: "x", groups: ["a", "b"] },
{ name: "y", groups: ["a"] }
],
b: [
{ name: "x", groups: ["a", "b"] },
{ name: "z", groups: ["b"] }
]
}
I'm wondering whether any programming languages have such a utility in their standard library, and if they do, what is the usual name?
Here's a possible JavaScript implementation in case the desired behavior isn't clear from the example:
const multiGroupBy = (items, callbackFn) =>
Object.fromEntries(
Object.entries(
Object.groupBy(
items.flatMap((item) => callbackFn(item).map((group) => [group, item])),
([group, _]) => group,
),
).map(([group, items]) => [group, items.map(([_, item]) => item)]),
)