1

Generate all combinations of object data

Function JavaScript 1 revisions 115 a year ago a year ago
function generateCombinations(combinations) {
	let results = [];

	const generate = (filteredCombinations, combination) => {
		combination = combination ? combination : {};
		const key = Object.keys(filteredCombinations)[0];
		if (Object.keys(filteredCombinations).length === 0 && filteredCombinations.constructor === Object)
			results.push(combination);
		else
			filteredCombinations[key].forEach(value => {
				generate(_.omit(filteredCombinations, key), {
					...combination,
					[key]: value
				});
			});
	};

	generate(combinations);

	return results;
};

Quick example

const combinations = {
  a: [1,2,3],
  b: [4,5,6],
  c: [7,8,9],
};

console.log(generateCombinations(combinations));

// Output:

[ {a: 1, b: 4, c: 7},
  {a: 1, b: 4, c: 8},
  {a: 1, b: 4, c: 9},
  {a: 1, b: 5, c: 7},
  {a: 1, b: 5, c: 8},
  {a: 1, b: 5, c: 9},
  {a: 1, b: 6, c: 7},
  {a: 1, b: 6, c: 8},
  {a: 1, b: 6, c: 9},
  {a: 2, b: 4, c: 7},
  {a: 2, b: 4, c: 8},
  {a: 2, b: 4, c: 9},
  {a: 2, b: 5, c: 7},
  {a: 2, b: 5, c: 8},
  {a: 2, b: 5, c: 9},
  {a: 2, b: 6, c: 7},
  {a: 2, b: 6, c: 8},
  {a: 2, b: 6, c: 9},
  {a: 3, b: 4, c: 7},
  {a: 3, b: 4, c: 8},
  {a: 3, b: 4, c: 9},
  {a: 3, b: 5, c: 7},
  {a: 3, b: 5, c: 8},
  {a: 3, b: 5, c: 9},
  {a: 3, b: 6, c: 7},
  {a: 3, b: 6, c: 8},
  {a: 3, b: 6, c: 9} ]