【问题标题】:Divide data into n groups distributed by some numeric property将数据分成按某个数值属性分布的 n 个组
【发布时间】:2015-09-02 20:46:45
【问题描述】:

假设我有以下数据样本。

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

【问题讨论】:

  • 您提出的解决方案有哪些“不起作用”?这是一个partitioning 问题,应该有可以适应您需求的算法。
  • 您尝试解决树数据结构的问题吗?我认为你的问题不是在 lowdash 中,你的主要问题是创建正确的算法和在 JavaScript 上编写代码

标签: javascript underscore.js lodash


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-28
    • 2012-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多