Js对数据实现分组GroupBy特性

我根据查找的资料,写了一个通用的

   GroupbyKey(array,key){
      let groups = {};
      let strResult =[];

      for(let  i=0; i<array.length ;i++){
        const  group =JSON.stringify(array[i][key]);
	//这里利用对象的key值唯一性的,创建数组
        groups[group] = groups[group] || [];
        groups[group].push(array[i]);
      }

      Object.keys(groups).map(u =>{
        groups[u].map(p =>{
          strResult.push(p);
        })
      });
      return strResult;
    }
	

array是如下类型

     list : [
        {
        "name": "John",
        "Average": 15,
        "High": 10,
        "DtmStamp": 1358226000000
        }
        ,
        {
          "name": "Jane",
          "Average": 16,
          "High": 92,
          "DtmStamp": 1358226000000
        }
        ,
        {
          "name": "Jane",
          "Average": 18,
          "High": 92,
          "DtmStamp": 1358226060000
        }
      ]

调用方法如下,以哪个键值分组就传那个键值属性名

 const results = this.GroupbyKey(list,"name");
posted @ 2021-06-27 12:01  寒冷的雨呢  阅读(560)  评论(0编辑  收藏  举报