数组里面数据分组排序

转换前数据

[{
    "type": "A",
    "month": "2019-03",
    "amount": 200,
    "username": "a001"
  },
  {
    "type": "A",
    "month": "2019-03",
    "amount": 1200,
    "username": "a002"
  }
  {
    "type": "A",
    "month": "2019-02",
    "amount": 300,
    "username": "a001"
  }
  {
    "type": "B",
    "month": "2019-02",
    "amount": 200,
    "username": "b001"
  },
  {
    "type": "C",
    "month": "2019-03",
    "amount": 200,
    "username": "c001"
  }
]

转换后数据

[
  {
    "month": "2019-02",
    "list": [{
      "type": "A",
      "info": [{
        "amount": 300,
        "username": "a001"
      }]
    },{
      "type": "B",
      "info": [{
        "amount": 200,
        "username": "b001"
      }]
    }]
  },{
    "month": "2019-03",
    "list": [{
      "type": "A",
      "info": [{
        "amount": 1200,
        "username": "a002"
      },{
        "amount": 200,
        "username": "a001"
      }]
    },{
      "type": "C",
      "info": [{
        "amount": 200,
        "username": "c001"
      }] 
    }
  }
]

实现如下:

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}
const groups = groupBy(arr,'month');
const final = Object.entries(groups).map(([month,e]) => {
  return {
    month,
    list: Object.entries(groupBy(e,'type')).map(([type,el]) => ({
      info: el,
      type
    }))
  }
})
console.log(final)

转载于:https://www.cnblogs.com/zeng-zhi/p/10512160.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现JS数组相同数据分组可以按照以下步骤进行: 1. 遍历原始数组,使用一个空对象或Map来存储每个元素对应的分组数组。假设我们将元素作为key,分组数组作为value。 2. 在遍历过程中,判断当前元素是否已经存在于分组的对象中。 3. 如果不存在,将当前元素作为key,创建一个新的数组作为value,并将当前元素添加到该数组中。 4. 如果已经存在,根据当前元素获取对应的分组数组,然后将当前元素添加到该数组中。 5. 最后,将所有的分组数组提取出来,作为最终的结果返回。 以下是一个示例代码: ```javascript function groupArray(arr) { var groups = {}; for (var i = 0; i < arr.length; i++) { var currentElement = arr[i]; if (groups.hasOwnProperty(currentElement)) { groups[currentElement].push(currentElement); } else { groups[currentElement] = [currentElement]; } } var result = []; for (var key in groups) { result.push(groups[key]); } return result; } var arr = [1, 2, 3, 2, 4, 1, 5, 4, 6]; var groupedArray = groupArray(arr); console.log(groupedArray); ``` 上述代码中,我们使用了一个空对象`groups`来存储每个元素对应的分组数组。遍历原始数组时,判断当前元素是否已经存在于`groups`对象中,如果存在,则将当前元素添加到对应分组数组中;如果不存在,则创建一个新的数组,并将当前元素作为key,该数组作为value。最后,将所有的分组数组提取出来,作为最终的结果返回。 以上就是用300字中文回答JS数组相同数据分组的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值