如何优化阵列分组?

时间:2018-02-24 15:55:37

标签: javascript

我有一个不断更新的数组,因此有必要更新其分组。数组示例:

[
 {
    "price": 2419.62,
    "amount": 0.0266
  },
  {
    "price": 1927.52,
    "amount": 0.0217
  },
  ...
]

我尝试了不同的选择。目前这个选项是最快的:

      const points = [
           {
              "price": 2419.62,
              "amount": 0.0266
            },
            {
              "price": 1927.52,
              "amount": 0.0217
            },
            ...
          ];
      const range = 500;
      const spread = 1800;
      const countGroup = 250;
      const sizeUnitGroup = range / countGroup;
      const groups = {};
      for (let i = 0;  i < countGroup; i++){
        groups[i] = [];
        try {
          points.forEach((item, id) => {
            if (item.price > spread + (i*sizeUnitGroup) && item.price <= spread + (i*sizeUnitGroup + sizeUnitGroup)){
              groups[i].push(item);
              points.splice(id, 1);
            }
            if (item.price > (spread + (i*sizeUnitGroup + sizeUnitGroup))) throw BreakException;
          });
        } catch (e) {
        }
      }

但即使这样,这个功能也能运作太久。任何想法如何优化?

1 个答案:

答案 0 :(得分:3)

您可以计算将值推送到所需广告位的时间间隔。

var points = [
        { price: 2419.62, amount: 0.0266 },
        { price: 1927.52, amount: 0.0217 },
        { price: 1800, amount: 0.07 },              // -1 not in result
        { price: 1800.000000000001, amount: 0.07 }, //  0
        { price: 1802, amount: 0.07 },              //  0
    ],
    range = 500,
    spread = 1800,
    countGroup = 250,
    sizeUnitGroup = range / countGroup,
    groups = {};

points.forEach((item, id) => {
    var i = Math.ceil((item.price - spread- sizeUnitGroup) / sizeUnitGroup);
    if (i >= 0 && i < countGroup) {
        groups[i] = groups[i] || [];
        groups[i].push(item);
    }
});

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