将数据划分为由一些数字属性分配的n个组

时间:2015-09-02 20:46:45

标签: javascript underscore.js lodash

说我有以下数据样本。

[
  { _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个组?

1 个答案:

答案 0 :(得分: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()&amp; _.reduce()
Original article on Russian (for php)