2016-12-12 37 views
-2

我在這種形式的陣列...遞歸唯一的JavaScript方法?

  • ARR [itemDescription]
    • [0] someValue1
    • [1] someotherValue1
  • ARR [itemDescription]
    • [0] someValue2
    • [1] someotherValue2
  • ARR [itemDescription]
    • [0] someValue3
    • [1] someotherValue3
  • ....

現在我將喜歡生成所有可能的變體,其中第一個項目與其他元素相結合,第二個元素組合在一起d與其他元素等。像:

  • [someValue1] [someValue2] [someValue3]
  • [someValue1] [someotherValue2] [someValue3]
  • [someValue1] [someotherValue2] [someotherValue3]
  • ....

總結一下,用於如下因素輸入數組:

[[11, 12], [21, 22], [31, 32]]; 

我需要獲得一個輸出數組,如

[[11, 21, 31], [11, 21, 32], [11, 22, 31], [11, 22, 32], [12, 21, 31], [12, 21, 32], [12, 22, 31], [12, 22, 32]]; 

有人能幫助我,我會怎麼做到這一點在JavaScript?

非常感謝!

+0

那你試試這麼遠嗎?放下一些代碼,否則你會得到低價。 – TigOldBitties

+0

歡迎來到SO。請訪問[幫助]並參加[導覽],查看要詢問的內容和方法。提示:投入工作量和代碼 – mplungjan

+0

兩個嵌套'for'循環。 – nicovank

回答

0

我提出這個解決方案。要決定選擇子陣列iside輸入數組的索引,我用數組維模全球指數:

var input = [[11, 12], [21, 22], [31, 32]]; 
 
var dim = Math.pow(2, input.length); 
 
var output = new Array(dim); 
 
output.fill(0); 
 
input.forEach((x,i) => { 
 
    var limit = dim/Math.pow(2, i+1); 
 
    output.forEach((y,j,arr) => { 
 
    var index = Math.floor((j+1)/limit) % 2; 
 
    if (i === 0) 
 
     arr[j] = [x[index]]; 
 
    else 
 
     arr[j].push(x[index]); 
 
    }); 
 
}); 
 
console.log(output);