簡體   English   中英

遞歸 flatMap

[英]Recursive flatMap

我試圖弄清楚如何將以下 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。

在您的示例中,您在各自的變量中跟蹤了array1_itemarray2_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));

一種方法是使用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));

編輯:我知道你要求遞歸。 如果這是一項學校任務,那么也許您必須使用遞歸,否則我建議盡可能避免遞歸,因為它往往會使事情變得更加復雜。 (當然,這是一般規則,與所有規則一樣,它也有一些例外。)

您可以使用遞歸自底向上方法一次 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
    });
  })
}

您可以使用遞歸使您的函數動態化。 我的解決方案是,您需要創建一個帶有三個參數(數組、索引、結果)的函數,一遍又一遍地調用您的函數,直到您完成對所有數組對象的迭代。 例如:

 function getPermutations(array, index = 0, prev = "") { // if the current index is lower than array length, keep calling the function if (index < array.length - 1) { return array[index].options.flatMap(item => { // if the previous value is empty, send the current item const current = prev ? `${prev} ${item}` : item; // resend the current value for the next iteration return getPermutations(array, index + 1, current); }); } else { // end of the iteration return array[index].options.flatMap(item => `${prev} ${item}`); } } let object = [{ "options": ['blue', 'gray', 'green'] }, { "options": ['large', 'medium', 'small'] }, { "options": ['wood', 'steel', 'pastic'] }]; console.log('Permutations', getPermutations(object));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM