Write a function “groupBy(array, callback)”

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

     var list = [{id: "102", name: "Alice"},
                  {id: "205", name: "Bob", title: "Dr."},
                  {id: "592", name: "Clyde", age: 32}];
    
    console.log(groupBy(list, function(i) { return i.id; }));
    console.log(groupBy(list, function(i) { return i.name.length; }));
    

    Here's a link to working example: https://codepen.io/pablo-tavarez/pen/NwjrEZ?editors=0012

    function groupBy(list, callback) {
      var output = {};
      var key
        , i = 0;
    
      // iterate over list of objects
      for ( ; i < list.length; i++ ) {
        // pass the current item to callback and get (current) key
        key = callback(list[i]);
    
        if (output[key]) {
          // handle duplicate keys without overriding -- (optionally make all key value Arrays)
          output[key] = [output[key]];
          output[key].push(list[i]);
        }
        else {
          output[key] = list[i];
        }
      }
    
      return output;
    }
    

提交回复
热议问题