我試圖弄清楚如何將以下 javascript 函式轉換為將遞回執行flapMap的動態函式。
function getPermutations(object) {
let array1 = object[0].options,
array2 = object[1].options,
array3 = object[2].options;
return array1.flatMap(function(array1_item) {
return array2.flatMap(function(array2_item) {
return array3.flatMap(function(array3_item) {
return array1_item ' ' array2_item ' ' array3_item;
});
});
});
}
let object = [{
"options": ['blue', 'gray', 'green']
}, {
"options": ['large', 'medium', 'small']
}, {
"options": ['wood', 'steel', 'pastic']
}];
console.log('Permutations', getPermutations(object));
在這個例子中,我將 3 個陣列發送到函式中,這就是為什么它有 3 次flapMap 迭代。作業正常,但我試圖使它成為動態的,所以我可以傳遞一個動態陣列,并且該函式將根據陣列遞回地執行flapMap。
uj5u.com熱心網友回復:
在您的示例中,您在各自的變數中跟蹤array1_item,array2_item和 co 。您可以將它們移動到一個陣列(具有動態大小;我稱之為_prevItems)并將它們作為引數傳遞給遞回呼叫。
function getPermutations(objects, _prevItems = []) {
// join the items at the end of the recursion
if (objects.length === 0)
return _prevItems.join(' ')
// call again with all but the first element, and add the current item to _prevItems
return objects[0].flatMap(item => getPermutations(objects.slice(1), [..._prevItems, item]))
}
let objects = [['blue', 'gray', 'green'], ['large', 'medium', 'small'], ['wood', 'steel', 'pastic']];
console.log('Permutations', getPermutations(objects));
uj5u.com熱心網友回復:
一種方法是使用reduce。
您想將選項串列減少為一個排列串列。
function getPermutations(list) {
return (
list
// First map to list of options (list of list of strings)
.map((item) => item.options)
// Then reduce. Do not set any initial value.
// Then the initial value will be the first list of options (in
// our example, ["blue", "gray", "green"])
.reduce((permutations, options) => {
return permutations.flatMap((permutation) =>
options.map((option) => permutation " " option)
);
})
);
}
// Renamed this to list, since it is an array and not an object
const list = [
{ options: ["blue", "gray", "green"] },
{ options: ["large", "medium", "small"] },
{ options: ["wood", "steel", "pastic"] },
];
console.log("Permutations", getPermutations(list));
編輯:我知道你要求遞回。如果這是一項學校任務,那么也許您必須使用遞回,否則我建議盡可能避免遞回,因為它往往會使事情變得更加復雜。(當然,這是一般規則,與所有規則一樣,它也有一些例外。)
uj5u.com熱心網友回復:
您可以使用遞回自底向上方法一次 flatMap 兩個陣列,并從最后構建您的字串
const getPermutations = (array) => {
if(array.length === 1)
return array[0].options;
const prefixItems = array[0].options;
const suffixItems = getPermutations(array.slice(1));
return prefixItems.flatMap(prefix => {
return suffixItems.flatMap(suffix => {
return prefix ' ' suffix
});
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/346427.html
標籤:javascript
