DEV Community

Discussion on: A 12-Line JavaScript Function to Get All Combinations of an Object's Properties

Collapse
 
dtinth profile image
Thai Pangsakulyanont

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:

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
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nas5w profile image
Nick Scialli (he/him)

ooo that's fancy!

Collapse
 
romainblatrix profile image
Romain Blatrix

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 }))
      ),
    [{}]
  );
Enter fullscreen mode Exit fullscreen mode

thanks for the inspiration :)