2012-12-06 59 views
0

無法弄清楚如何使用所有匹配創建數組。我想我需要一個遞歸函數。使用所有唯一組合創建數組

我喜歡從下面的JSON獲取所有值,並創建一個包含所有值組合的數組。 可能有更多或更少的模型(Name4)以及更多或更少的值。 有什麼幫助嗎?

var models = [ 
    { 
     name: 'Name1', 
     values: [ 
      'Title1Value1', 
      'Title1Value2', 
      'Title1Value3' 
     ] 
    }, 
    { 
     name: 'Name2', 
     values: [ 
      'Title2Value1', 
      'Title2Value2' 
     ] 
    }, 
    { 
     name: 'Name3', 
     values: [ 
      'Title3Value1', 
      'Title3Value2' 
     ] 
    } 
]; 

// Output array 
var matches = [ 
    [ 'Title1Value1', 'Title2Value1', 'Title3Value1' ], 
    [ 'Title1Value1', 'Title2Value1', 'Title3Value2' ], 
    [ 'Title1Value1', 'Title2Value2', 'Title3Value1' ], 
    [ 'Title1Value1', 'Title2Value2', 'Title3Value2' ], 
    [ 'Title2Value2', 'Title2Value1', 'Title3Value1' ], 
    [ 'Title1Value2', 'Title2Value1', 'Title3Value2' ], 
    [ 'Title1Value2', 'Title2Value2', 'Title3Value1' ], 
    [ 'Title1Value2', 'Title2Value2', 'Title3Value2' ], 
    [ 'Title1Value3', 'Title2Value1', 'Title3Value1' ], 
    [ 'Title1Value3', 'Title2Value1', 'Title3Value2' ], 
    [ 'Title1Value3', 'Title2Value2', 'Title3Value1' ], 
    [ 'Title1Value3', 'Title2Value2', 'Title3Value2' ] 
]; 

回答

0
var indices = []; 
var lengths = []; 
for (i = 0; i<models.length; i++) { 
    indices[i] = 0; 
    lengths[i] = models[i].values.length; 
} 
var matches = []; 
while (indices[0] < lengths[0]) { 
    var row = []; 
    for (i = 0; i<indices.length; i++) { 
     row.push(models[i].values[indices[i]]); 
    } 
    matches.push(row); 
    /* Cycle the indexes */ 
    for (j = indices.length-1; j >= 0; j--) { 
     indices[j]++; 
     if (indices[j] >= lengths[j] && j != 0) { 
      indices[j] = 0; 
     } else { 
      break; 
     } 
    } 
} 
+0

這就是黃金。謝謝! – brasimon