Write a function “groupBy(array, callback)”

前端 未结 7 1052
醉梦人生
醉梦人生 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:27

    Solution with pure JS:

    var list = [{
        id: "102",
        name: "Alice"
      },
      {
        id: "205",
        name: "Bob",
        title: "Dr."
      },
      {
        id: "592",
        name: "Clyde",
        age: 32
      }
    ];
    
    function groupBy(array, callback) {
      return array.reduce(function(store, item) {
        var key = callback(item);
        var value = store[key] || [];
        store[key] = value.concat([item]);
        return store;
      }, {})
    }
    
    console.log('example 1: ', groupBy(list, function(i) { return i.id; }));
    console.log('example 2: ', groupBy(list, function(i) { return i.name.length; }));

提交回复
热议问题