2015-09-02 56 views
3

假設我有以下數據樣本。將數據劃分爲由某些數字屬性分配的n個組

[ 
    { _id: "1", weight: 3 }, 
    { _id: "2", weight: 3 }, 
    { _id: "3", weight: 4 }, 
    { _id: "4", weight: 1.5 } 
] 

我想借此數據,並通過財產劃分它weight,使得它作爲密切各組中的性能平衡。在這種情況下,最後的結果應該是這樣的:

groupByProperty(fakeData, 2, 'weight'); 
[ 
    [{ _id: "1", weight: 3}, { _id: "2", weight: 3}], // total: 6 
    [{ _id: "3", weight: 4}, {_id: "4", weight: 1.5}] // total: 5.5 
] 

也就是說,權重應該是每個組中的類似/均勻越好。是否有捷徑可尋?我已經玩弄了一些lodash來完成它

groupByProperty = function (data, divisions, property) { 
    let compartments = _.range(divisions); 
    _.each(fakeData, (d) => { 
    _(compartments) 
     .sortBy((i) => _.sum(_.pluck(i, 'weight'))) 
     .reverse() 
     .first() 
     .push(product); 
    }); 
    return compartments; 
} 

不真的工作,但它是一個開始。

如何將數據分成由JavaScript中屬性分佈的n組?

+4

什麼 「並沒有真正的工作」 你的建議的解決方案?這是[分區](https://en.wikipedia.org/wiki/Partition_problem)問題,應該有一些算法可以適應您的需求。 –

+0

您是否嘗試解決樹數據結構的問題?我認爲你的問題不是在lowdash中,你主要的問題是創建正確的算法並在JavaScript上編寫代碼 – khusnetdinov

回答

1

功能:

function groupByProperty(data, divisions, field) { 
    divisions = Math.round(divisions); 
    var l = data.length; 

    if(divisions <= 0 || l < divisions) { 
     return data; 
    } else { 
     var out = []; 
     for(var i = 0; i < divisions; i++){ 
      out.push([]); 
     } 

     data = _.sortBy(data, function(p){return -p[field];}); 

     for(var i = 0; i < l; i++){ 
      var record = data[i]; 

      out = _.sortBy(out, function(p){return _.reduce(p, function(memo, x){return memo + x[field];}, 0);}); 

      out[0].push(record); 
     } 
     return out; 
    } 
}; 

函數測試:

var result = groupByProperty(data, 2, 'weight'); 
console.log(result); 
for(var i = 0; i < result.length; i++){ 
    console.log(_.reduce(result[i], function(memo, p){ return memo + p.weight;}, 0)); 
} 

結果爲2,3,4個區劃:

5.5, 6 
4.5, 3, 4 
1.5, 3, 3, 4 

使用:_.sortBy() & _.reduce()
Original article on Russian (for php)