数据分组


  const people=[
    {name:'Alice',age:30,sex:'female'},
    {name:'Bob',age:25,sex:'male'},
    {name:'Charlie',age:30,sex:'male'},
    {name:'Diana',age:25,sex:'female'},
    {name:'Eva',age:25,sex:'female'},
    {name:'Frank',age:25,sex:'male'},
    {name:'Grace',age:20,sex:'male',address:{
      province: '黑龙江',city:'哈尔滨'
      }},
  ];
  console.table(people);
  function groupBy(arr,proName) {
    const result = {};
    for(let item of arr){
      const key = item[proName];
      if(!result[key]){
        result[key]=[];
      }
      result[key].push(item);
    }
    return result;
  }
  // 按照年龄分组
  // console.log(groupBy(people,'age'));
  // 按照性别分组
  // console.log(groupBy(people,'sex'));

还没有结束、如果按照省份分组那么那个函数不通用

改进

  function groupBy(arr,generateKey) {
    const result = {};
    for(let item of arr){
      const key = generateKey(item);
      if(!result[key]){
        result[key]=[];
      }

      result[key].push(item);
    }
    return result;
  }


  //新的按照年龄分组
  console.log(groupBy(people,(item)=>item.age));
  //新的按照性别分组
  console.log(groupBy(people,(item)=>item.sex));
  //按 年龄-性别分组
  console.log(groupBy(people,(item)=>`${item.age}-${item.sex}`));
  //按 奇偶数分组
  const arr = [34,6,323,2,1,5];
  console.log(groupBy(arr,(item)=>(item%2 ===0 ?'偶':'奇')));

最终

参数归一

  function groupBy(arr,generateKey) {
    if(typeof generateKey === 'string'){
      const proName =  generateKey;
      generateKey = (item)=>item[proName];
    }
    const result = {};
    for(let item of arr){
      const key = generateKey(item);
      if(!result[key]){
        result[key]=[];
      }

      result[key].push(item);
    }
    return result;
  }
  console.log(groupBy(people,'sex'));
Last modification:January 22, 2024
如果觉得我的文章对你有用,请随意赞赏