我想找到 n-array 的 options-property 的所有组合。在示例中,数组的长度为 3,但该函数也应该使用更大或更小的数组大小。
var arr = [{
name: 'Fruit',
options: ['apple', 'kiwi']
}, {
name: 'Food',
options: ['bread', 'rice']
}, {
name: 'Drink',
options: ['water', 'cola']
}]
Run Code Online (Sandbox Code Playgroud)
结果应结果打印以下语句
Fruit: apple | Food: bread | Drink: water
Fruit: apple | Food: bread | Drink: cola
Fruit: apple | Food: rice | Drink: water
Fruit: apple | Food: rice | Drink: cola
Fruit: kiwi | Food: bread | Drink: water
Fruit: kiwi | Food: bread | Drink: cola
Fruit: kiwi | Food: rice | Drink: water
Fruit: kiwi | Food: rice | Drink: cola
Run Code Online (Sandbox Code Playgroud)
我已阅读此答案Find All Combinations (Cartesian product) of JavaScript array values,但在我的示例中,数组是一个对象,我无法弄清楚如何获取属性。这是我到目前为止:
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
} else if (arr.length ===1){
return arr[0].options;
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var c in allCasesOfRest) {
for (var i = 0; i < arr[0].options.length; i++) {
console.log(arr[0].name, ": ", arr[0].options[i], "| ", allCasesOfRest[c])
}
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Food : bread | water
Food : rice | water
Food : bread | cola
Food : rice | cola
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
您可以获取值,构建笛卡尔积并映射属性。
var array = [{ name: 'Fruit', options: ['apple', 'kiwi'] }, { name: 'Food', options: ['bread', 'rice'] }, { name: 'Drink', options: ['water', 'cola'] }],
keys = array.map(({ name }) => name),
result = array
.map(({ options }) => options)
.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] }))));
console.log(result);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |