按价格十进制分组值,按数量分组总和

时间:2019-02-22 07:15:14

标签: javascript arrays object group-by

我想在javascript中按价格对数组对象进行分组,按数量对总数进行分组?例如:

var array=[
  {price:0.112,qty:1},
  {price:0.218,qty:1},
  {price:0.216,qty:1},
  {price:0.321,qty:1},
  {price:0.325,qty:2},
  {price:0.335,qty:2},
  {price:0.536,qty:1}
]

将价格按pricedecimal=2分组后,我将得到新的数组,如:

价格decimal=2,get_number = 3是预期的输出:

[
  {price:0.32,qty:3},
  {price:0.33,qty:2},
  {price:0.53,qty:1}
]

价格小数位= 1,预期获得get_number = 2:

[
  {price:0.3,qty:5},
  {price:0.5,qty:1}
]

1 个答案:

答案 0 :(得分:0)

您可以使用简单的 Array#forEach() method 调用来迭代array的值,并使用 .toFixed()method通过price对其进行过滤< / strong>:

let result = [];
array.forEach(function(a) {
  a.price = a.price.toFixed(1);
  if (result.some(x => x.price === a.price)) {
    result.find(x => x.price === a.price).qty += a.qty;
  } else {
    result.push(a);
  }
});

.toFixed(1)此处将仅使用一个小数位比较价格,如果要与两个小数位进行比较,则只需将其更改为.toFixed(2)

演示:

这是一个有效的代码段:

var array=[
  {price:0.112,qty:1},
  {price:0.218,qty:1},
  {price:0.216,qty:1},
  {price:0.321,qty:1},
  {price:0.325,qty:2},
  {price:0.335,qty:2},
  {price:0.536,qty:1}
]

let result = [];
array.forEach(function(a) {
  a.price = a.price.toFixed(1);
  if (result.some(x => x.price === a.price)) {
    result.find(x => x.price === a.price).qty += a.qty;
  } else {
    result.push(a);
  }
});

console.log(result);