Write a function “groupBy(array, callback)”

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

    Heres a link to the code: http://rextester.com/KROB29161

    function groupBy(list, callback) {
      // Declare a empty object
      var obj = {};
    
      // We then loop through the array
      list.forEach(function(item) {
        // We define the key of the object by calling the 
        // callback with the current item
        var key = callback(item);
    
        // If the field exists, add this item to it
        if (obj[key]) {
          obj[key] = obj[key].concat(item);
        } else {
    
          // If the field does not exist, create it and this value
          // as an array 
          obj[key] = [item];
        }
      });
      return obj;
    }
    
    0 讨论(0)
提交回复
热议问题