Reputation: 673
I'm building an array of objects out of the permutations of the entries in some arrays. My first stab at the code is below, it should help to illustrate what I'm trying to achieve:
permutationsArray = (array1, array2, array3) => {
const arrayOfObjects = [];
for (let i = 0; i < array1.length; i++) {
for (let j = 0; j < array2.length; j++) {
for (let k = 0; k < array3.length; k++) {
arrayOfObjects.push({
aConstant: 'some constant',
key1: array1[i],
key2: array2[j],
key3: array3[k],
});
}
}
}
return arrayOfObjects;
};
I'm really unhappy with having nested for
loops to achieve this. Alternatives I have looked at are:
I'm looking for input as to whether I'm going in the right direction with solving this. Ideally I want to get to the point where I can supply as many arrays as I wanted.
A big problem I'm seeing is how to name the keys with recursion.
Upvotes: 2
Views: 2201
Reputation: 48357
First of all, that's not a problem with permutations
, it's exactly Cartesian product
.
In set
theory (and, usually, in other parts of mathematics), a Cartesian product
is a mathematical operation that returns a set
from multiple sets.
You can achieve that using ES6
features like map and reduce methods.
function cartesianProduct(...arrays) {
return [...arrays].reduce((a, b) =>
a.map(x => b.map(y => x.concat(y)))
.reduce((a, b) => a.concat(b), []), [[]]);
}
console.log(cartesianProduct([1, 2], [3, 4], [5, 6]));
Upvotes: 3