The answer in Cartesian product of multiple arrays in JavaScript does not answer my question since my implementation is quite similar to what is said there and I'm only asking about ways to optimize this implementation.
I have two arrays of objects and I want to create one array of objects representing all possible combinations of the first two arrays. To make things clear let's say I have an array of products in supply, an array of products in demand, and I want to see every possible combination of supply and demand. I'm using node.js but the problem is language agnostic.
So if I have:
const supply = [
{
id: '1',
name: 'chair'
},
{
id: '2',
name: 'desk'
}
];
const demand = [
{
id: '3',
name: 'couch'
},
{
id: '4',
name: 'desks'
}
]
I want the output to be:
[
{
id: '1-3',
supply: 'chair',
demand: 'couch'
},
{
id: '1-4',
supply: 'chair',
demand: 'desks'
},
{
id: '2-3',
supply: 'desk',
demand: 'couch'
},
{
id: '2-4',
supply: 'desk',
demand: 'desks'
}
]
To achieve this I implemented the following:
return supply.reduce((acc, supply) => {
return acc.concat(
demand.map(demand => {
return {
id: `${supply.id}-${demand.id}`,
supply: supply.name,
demand: demand.name
}
})
)
}, []);
This works fine, but as my data sets get bigger (right now I have a couple of hundred items in each array, and I'm going to have more soon) it can also get very slow.
Is there any way to optimize this? I can't think of a way to achieve this without iterating over the one array and then over the other for each item of the first array. But maybe I'm missing something?
Please let know if I can provide more information on this.
Any help will be greatly appreciated!