zoukankan      html  css  js  c++  java
  • js分组求和

    后端返回的数据是所有的,但是前端需要的数据是需要分组并且进行计算求和的

    // 数组分组求和
      let groupSum = {
        groupBy: function (array, callback) {
          return new Promise((resolve) => {
            let groups = {};
            array.forEach(item => {
              let group = JSON.stringify(callback(item));
              groups[group] = groups[group] || [];
              groups[group].push(item);
            });
            let res = Object.keys(groups).map(group => {
              return groups[group];
            });
            resolve(res)
          })
        },
        getSum: function (arr,bykey) {
          return new Promise((resolve) => {
            let res = this.groupBy(arr, function (item) {
              return item.shopId
            }).then(res => {
              console.log(res)
              let resultSum = res.map(item => {
                let sum = item.reduce((total, curr) => {
                  return total + curr[bykey]
                }, 0);
                return sum
              })
              return resultSum
            })
            resolve(res)
          })
        }
      }
      let testArr = [
        { shopId: 1, shopName: '测试', money: 0, },
        { shopId: 2, shopName: '123', money: 1 },
        { shopId: 1, shopName: '测试', money: 2 },
        { shopId: 1, shopName: '测试', money: 3 },
        { shopId: 2, shopName: '123', money: 4 },
        { shopId: 1, shopName: '测试', money: 5 },
        { shopId: 2, shopName: '123', money: 6 },
      ]
      groupSum.getSum(testArr,'money').then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
  • 相关阅读:
    BZOJ 1500 维修数列
    BZOJ 1501 智慧珠游戏
    BZOJ 1507 Editor
    BZOJ 3223 文艺平衡树
    BZOJ 3224 普通平衡树
    BZOJ 3196 二逼平衡树
    BZOJ 1048 分割矩阵
    BZOJ 1047 理想的正方形
    BZOJ 1046 上升序列
    BZOJ 1045 糖果传递
  • 原文地址:https://www.cnblogs.com/sunzhihua/p/15324856.html
Copyright © 2011-2022 走看看