'Cartesian product for an array of json objects
How can I produce all of the combinations of the values in an array of the of Objects.
var input = [
{ "colour" : "red",
"material" : "cotton" ,
"shape" : "round"
},
{ "colour" : "green",
"material" : "wool" ,
"shape" : "square"
}
];
The expected output is the Cartesian product of all the options available, creating a new array with the same keys.
var expected = [
{ 'colour': 'red', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'red', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'square' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'square' }
];
Solution 1:[1]
I would approach this in two steps:
Step 1: collect all values for each key
var options = {};
input.forEach(function (item)
{
for (var prop in item)
{
if (options[prop])
{
options[prop].push(item[prop]);
} else
{
options[prop] = [item[prop]];
}
}
});
console.log(options);
Which will give
{ colour: [ 'red', 'green' ],
material: [ 'cotton', 'wool' ],
shape: [ 'round', 'square' ] }
Step 2: Create the cartesian product by using a triple-nested iteration:
let result = [{}];
for (var prop in options)
{
// For each object in the existing list...
result = result.map(function (object)
{
// ... create copies of that object for each option for the current key
return options[prop].map(function (option)
{
let newObject = Object.assign({}, object)
newObject[prop] = option
return newObject
})
})
// The result is an array of arrays of objects, so flatten it
.flat()
}
console.log(result)
Which gives
[ { colour: 'red', material: 'cotton', shape: 'round' },
{ colour: 'red', material: 'cotton', shape: 'square' },
{ colour: 'red', material: 'wool', shape: 'round' },
{ colour: 'red', material: 'wool', shape: 'square' },
{ colour: 'green', material: 'cotton', shape: 'round' },
{ colour: 'green', material: 'cotton', shape: 'square' },
{ colour: 'green', material: 'wool', shape: 'round' },
{ colour: 'green', material: 'wool', shape: 'square' } ]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aaron Dunigan AtLee |
