2017-03-15 90 views
3

我尋找以下片斷一個廣義解::遞歸通過動態陣列

var d = [[1,2,3], [1,2], [1,2,3,4,5,6]]; 
 

 
d[0].map((val1, index1) => { 
 
    d[1].map((val2, index2) => { 
 
     d[2].map((val3, index3) => { 
 
      console.log(index1, index2, index3); 
 
     }) 
 
    }) 
 
});

這裏此遊戲機爲3的數組元素的可能組合。

我們可以概括一下,比如說:

var d = [[1,2,3], [1,2], [1,2,3,4,5,6], [1,2,3,4]]; // k number of elements 

的僞代碼::

let processor = (d) => { 
    // implementation code 
    // output will be the combination for 4 array elements this time. 
} 

有人可以幫我設計的過程中的作用?尋找一個廣義的解決方案。任何幫助或領導是可觀的。

+0

遍歷'D'和使用'Array.isArray()',並遞歸調用該函數。對於每個元素,它會將它推送到一個結果數組中。 –

+1

我無法理解你要完成什麼,即使是在專門的情況下...... – pQuestions123

+1

你想要合併數組嗎?你的問題不清楚。你能解釋一下你試圖達到的目標嗎? –

回答

1

您可以使用迭代和遞歸方法。

var d = [[1, 2, 3], [1, 2], [1, 2, 3, 4, 5, 6]], 
 
    processor = array => { 
 
     var iter = p => p.length < array.length ? 
 
       array[p.length].forEach((_, i) => iter(p.concat(i))) : 
 
       console.log(p); 
 

 
     iter([]); 
 
    }; 
 

 
processor(d);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

你可以做如下:

var cart = (a,b) => a.reduce((p,c) => p.concat(b.map(e => [].concat(c,e))),[]); 
 
    arr = [[1,2,3], [1,2], [1,2,3,4,5,6], [8,9]], 
 
    res = arr.reduce(cart); 
 

 
console.log(JSON.stringify(res));

+1

令人印象深刻!.... – georg

+1

@georg這是一個遺憾,你刪除了你的答案。老實說,我相信這項工作必須由發電機組懶惰地完成。但在JS中,他們看起來不像在Haskell中那麼酷。 – Redu