At first I assumed it doing this requires a recursive-like algorithm, never thought of doing it that way!
Using flatMap, we can further reduce this down to 8 lines:
flatMap
function allCombinations(obj) { let combos = [{}] for (const [key, values] of Object.entries(obj)) { combos = combos.flatMap((combo) => values.map((value) => ({ ...combo, [key]: value })) ) } return combos }
ooo that's fancy!
or even shorter :
type PropObject = Record<string, unknown[]>; export const getCombinations = (obj: PropObject): PropObject[] => Object.entries(obj).reduce( (acc, [key, values]) => acc.flatMap((combo) => values.map((value) => ({ ...combo, [key]: value })) ), [{}] );
thanks for the inspiration :)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
At first I assumed it doing this requires a recursive-like algorithm, never thought of doing it that way!
Using
flatMap
, we can further reduce this down to 8 lines:ooo that's fancy!
or even shorter :
thanks for the inspiration :)