Write a function “groupBy(array, callback)”

前端 未结 7 1023
醉梦人生
醉梦人生 2020-12-06 19:52

I have a JavaScript task where I have to implement a function \"groupBy\", which, when given an array of objects and a function, returns an object w

7条回答
  •  爱一瞬间的悲伤
    2020-12-06 20:37

    Here is another approach using reduce:

     var list = [{
         id: "102",
         name: "Alice"
       },
       {
         id: "205",
         name: "Bob",
         title: "Dr."
       },
       {
         id: "592",
         name: "Clyde",
         age: 32
       }
     ];
    
    
    
     function groupBy(list, callback) {
       return list.reduce((acc, x) => {
         const key = callback(x);
         if (!acc[key]) {
           return {
             ...acc,
             [key]: [x]
           }
         }
         return {
           ...acc,
           [key]: [...acc[key], x]
         }
    
       }, {})
     }
    
    // callback functions
     function nameLength(obj) {
       return obj.name.length;
     }
    
     function objectProperty(obj) {
       return obj.id
     }
    
    
     console.log('group by name length:', groupBy(list, nameLength));
     console.log('group by Id:', groupBy(list, objectProperty));

提交回复
热议问题