reduce基本用法,js实现分组

1.reduce用法:

/***
* @desc-转换数组
* @param {arr}  
***/
let arr = ['1','2','3','4','5'];
temparr = arr.reduce((result,item,index)=>{
     result.push(item == 1? '周一' : item == 2 ? '周二' : item == 3? '周三' : item == 4 ? '周四' : '周五');
     return result;
},[]);
console.log(temparr);
/***
 *@desc-分组
 * @param {arr}  
***/
let arr = [
   {
       "activityAttendRegionId":"244860186500665344",
       "activityAttendRuleId":"",
       "activityId":"",
       "createdTime":null,
       "id":null,
       "multipleIntegral":1.1,
       "regionId":"7132b2aeb0964d52b8c2c8421f27fe8c",
       "regionName":"汽油的",
       "stationId":"10010100001",
       "stationName":"成都市天府广场加油站",
       "type":"2"
    },
    {
          "activityAttendRegionId":"244860186500665345",
          "activityAttendRuleId":"",
          "activityId":"",
          "createdTime":null,
          "id":null,
         "multipleIntegral":1.2,
          "regionId":"dbeb0f343fcc4e53aa20af7a06b44a2c",
          "regionName":"固额赠送",
         "stationId":"10010100001",
         "stationName":"成都市天府广场加油站",
         "type":"2"
     },
     {
         "activityAttendRegionId":"244860186500665346",
         "activityAttendRuleId":"",
         "activityId":"",
         "createdTime":null,
         "id":null,
         "multipleIntegral":1.1,
         "regionId":"e9abee2cebf443c4b3b7ae996283b091",
         "regionName":"汽油1",
         "stationId":"10010100002",
         "stationName":"成都市锦江区加油站",
         "type":"2"
     },
     {
        "activityAttendRegionId":"244860186500665347",
        "activityAttendRuleId":"",
        "activityId":"",
        "createdTime":null,
        "id":null,
        "multipleIntegral":1.2,
        "regionId":"37958946386f48d5979da6393aa2dc29",
        "regionName":"比例",
        "stationId":"10010100002",
        "stationName":"成都市锦江区加油站",
        "type":"2"
     },
     {
        "activityAttendRegionId":"244860186546802688",
        "activityAttendRuleId":"",
        "activityId":"",
        "createdTime":null,
        "id":null,
        "multipleIntegral":1.1,
        "regionId":"3377694414134fd685f16f4c4f0ae7fe",
       "regionName":"222",
       "stationId":"10010100005",
       "stationName":"现代通卡有限公司",
       "type":"2"
    }
 ];
function gropArr(arr){
   const s = new Set(); //实例化对象
   arr.forEach(item => s.add(item.stationId)); //添加值(Set可以去掉重复数据)
   let newdata = Array.from({ length: s.size }, () => []); //创建指定长度数组并添值
       arr.forEach(item => {
           let index = [...s].indexOf(item.stationId) //找到指定下标
           newdata[index].push(item);
       });
       return newdata;
 }
 console.log(gropArr(arr));

 

posted @ 2020-07-29 13:59  fate、hu  阅读(1082)  评论(0编辑  收藏  举报