'get all the combinations between x arrays
I have N arrays with objects inside. All objects has the same keys.
arr[
{values:val1,names:someName},
{values:val2,names:otherName},
]
arr2[
{values:valx,names:someNamex},
{values:valy,names:otherNamey},
]
I need to mix all the combinations between that N arrays. Something like this:
newArray[
{values:'val1''valx',names:'someName''someNamex'}
{values:'val1''valy',names:'someName''someNamey'}
{values:'val2''valx',names:'otherName''someNamex'}
{values:'val2''valy',names:'otherName''someNamey'}
]
I hope this can be helpful to find an answer to this problem.
Thanks for your time!
Solution 1:[1]
Presented below is one possible way to achieve the desired objective.
Code Snippet
const myArr1 = [
{values:'val1',names:'someName'},
{values:'val2',names:'otherName'},
];
const myArr2 = [
{values:'valx',names:'someNamex'},
{values:'valy',names:'otherNamey'},
];
const arrOfArr = [...Array(5).keys()].map(x => (
[...Array(3).keys()]
.map(k => ({
values: `val${x}${k}`,
names: `someName${x}${k}`
}))
));
//console.log(...arrOfArr);
const myConcat = (a, b, ...objs) => (
objs.flatMap((obj) => ({
values: `${a.values} ${b.values}`,
names: `${a.names} ${b.names}`
}))
);
const f = (a, b) => [].concat(...a.flatMap(d => b.flatMap(e => myConcat(d, e, []))));
const cartesian = (a, b, ...c) => (b ? cartesian(f(a, b), ...c) : a);
console.log(
'simple test case with only 2 arrays: ', cartesian(myArr1, myArr2), '\n\n\t******\n\n'
);
console.log(
'complex test case with 7 arrays some with 3 objects each: ',
cartesian(myArr1, myArr2, ...arrOfArr)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
- Adapts the cartesian-product answer as noted by pilchard to this context
- Invokes the cartesian method for given set of arrays
- Uses
.myConcat()to transform the result of concatenation to havevaluesandnamesstring-concatenated at a per-object level
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 | jsN00b |
