break array of objects into separate arrays based on a property

后端 未结 7 1140
太阳男子
太阳男子 2020-12-01 07:10

Say I have an array like this:

var arr = [
    {type:\"orange\", title:\"First\"},
    {type:\"orange\", title:\"Second\"},
    {type:\"banana\", title:\"Thi         


        
相关标签:
7条回答
  • 2020-12-01 08:00

    This is an easy job for Array.reduce(...):

    function groupBy(arr, property) {
      return arr.reduce(function(memo, x) {
        if (!memo[x[property]]) { memo[x[property]] = []; }
        memo[x[property]].push(x);
        return memo;
      }, {});
    }
    
    var o = groupBy(arr, 'type'); // => {orange:[...], banana:[...]}
    o.orange; // => [{"type":"orange","title":"First"},{"type":"orange","title":"Second"}]
    o.banana; // => [{"type":"banana","title":"Third"},{"type":"banana","title":"Fourth"}]
    

    Of course, if your target browser(s) do not support ECMAScript 262 5th edition then you'll have to implement "reduce" by yourself, or use a polyfill library, or choose another answer.

    [Update] Here's a solution that should work with any version of JavaScript:

    function groupBy2(xs, prop) {
      var grouped = {};
      for (var i=0; i<xs.length; i++) {
        var p = xs[i][prop];
        if (!grouped[p]) { grouped[p] = []; }
        grouped[p].push(xs[i]);
      }
      return grouped;
    }
    
    0 讨论(0)
提交回复
热议问题