combinate
combinate copied to clipboard
How would I reverse combinate?
Let's say I have a dataset like this:
[
{"admin": true, "color": "red", "mode": "light"},
{"admin": true, "color": "blue", "mode": "light"},
{"admin": true, "color": "green", "mode": "light"},
{"admin": false, "color": "red", "mode": "light"},
{"admin": false, "color": "blue", "mode": "light"},
{"admin": false, "color": "green", "mode": "light"},
{"admin": true, "color": "red", "mode": "dark"},
{"admin": true, "color": "blue", "mode": "dark"},
{"admin": true, "color": "green", "mode": "dark"},
{"admin": false, "color": "red", "mode": "dark"},
{"admin": false, "color": "blue", "mode": "dark"},
{"admin": false, "color": "green", "mode": "dark"}
]
How would I reverse the combination process to produce:
{
color: ["red", "blue", "green"],
admin: [true, false],
mode: ["light", "dark"],
}
I'm not expecting this tool to do it; I just wondered if you might have some insight.
@matthew-dean
function reverseCombinations<T, O extends Record<string, T>>(perms: O[]): Record<keyof O, T[]> {
const sets: Record<string, Set<O[keyof O]>> = {};
for (const perm of perms) {
for (const key in perm) {
if (!(key in sets)) {
sets[key] = new Set();
}
sets[key].add(perm[key]);
}
}
return Object.fromEntries(
Object.entries(sets).map(([key, set]) => [key, Array.from(set)])
) as Record<keyof O, T[]>;
}