小王同学
小王同学
发布于 2024-07-08 / 30 阅读
0

根据数组中对象value,进行对象分组

[
    {"name":"玫瑰","age":1},
    {"name":"大卫","age":8},
    {"name":"艾米丽","age":2},
    {"name":"查理","age":3},
    {"name":"鲍勃","age":10},
    {"name":"弗兰克","age":15},
    {"name":"艾丽斯","age":5},
    {"name":"琳达","age":10},
    {"name":"亚当","age":2},
    {"name":"凯特","age":8},
    {"name":"汤姆","age":5},
    {"name":"莉莉","age":1},
    {"name":"迈克尔","age":10},
    {"name":"艾米","age":3},
    {"name":"乔治","age":15},
    {"name":"艾伦","age":10},
    {"name":"安娜","age":2},
    {"name":"杰克","age":5},
    {"name":"莎拉","age":8},
    {"name":"约翰","age":15},
    {"name":"丽莎","age":10},
    {"name":"布莱恩","age":2},
    {"name":"凯丽","age":5},
    {"name":"豪尔赫","age":1},
    {"name":"艾丽","age":3},
    {"name":"帕特里克","age":8},
    {"name":"莉萨","age":2},
    {"name":"迪伦","age":1},
    {"name":"凯文","age":15},
    {"name":"艾娃","age":5},
    {"name":"乔","age":10},
    {"name":"安东尼","age":15},
    {"name":"莉娜","age":2}
  ]
let newArr = []   // 对数组对象value进行去重分组
  let obj = {}   // 新建对象
  
  1.第一种方式
  // 添加数组元素
  peoples.forEach(item => {
    if(!newArr.includes(item.age)){
      newArr.push(item.age)
    }
  }); 
  
  2.第二种方式使用set
  (1)new Set()
  (2)遍历对象,将key添加到set中
  
  // 对数组中元素分组  
  newArr.forEach(item => {
    obj[item] = peoples.filter(item1=>item1.age == item)
  });
  
  3.第三种reduce
  const people = [
  { name: "Alice", age: 21 },
  { name: "Max", age: 20 },
  { name: "Jane", age: 20 },
];

function groupBy(objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    const curGroup = acc[key] || [];

    return { ...acc, [key]: [...curGroup, obj] };
  }, {});
}

const groupedPeople = groupBy(people, "age");
console.log(groupedPeople);
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }