js根据数组中的某个属性进行分类

1、我们工作过程中常常会遇到根据数组中的某个属性进行分类比如从

arr = [
     { year: 2001, name: "张三" },
     { year: 2002, name: "李四" },
     { year: 2003, name: "王五" },
     { year: 2001, name: "张思" }
 ]

转换成 下面这种

[
     {
        2001: [
             { year: 2001, name: "张三" },
             { year: 2001, name: "张思" }]
     },
     {
         2002: [
             { year: 2002, name: "李四" }
         ]
     },
     {
         2003: { year: 2003, name: "王五" }
     }
 ]

就是根据 year 属性来进行分类,并且作为新数据的key

2、实现这个很简单,三行代码就够了

 let obj = arr.reduce((pre, cur) => {
        (pre[cur.year] || (pre[cur.year] = [])).push(cur);
         return pre
     }, [])

输出obj 即可

你可能感兴趣的:(前端,javascript,前端)