从数组值生成笛卡尔乘积对象 [英] Generation cartesian product objects from array values
问题描述
我正在根据某些数组中条目的排列来构建对象数组.下面是我在代码中的第一个刺入点,它应该有助于说明我要实现的目标:
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;
};
我非常不高兴嵌套有for
循环来实现这一目标.我看过的替代方法是:
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.
推荐答案
首先,permutations
没问题,完全是Cartesian product
.
First of all, that's not a problem with permutations
, it's exactly Cartesian product
.
在set
理论(通常在数学的其他部分)中,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.
您可以使用ES6
功能(例如减少方法.
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]));
这篇关于从数组值生成笛卡尔乘积对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!