How to group an array of objects by key

后端 未结 24 2787
后悔当初
后悔当初 2020-11-21 05:13

Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav

相关标签:
24条回答
  • 2020-11-21 05:30

    Building on the answer by @Jonas_Wilms if you do not want to type in all your fields:

        var result = {};
    
        for ( let { first_field, ...fields } of your_data ) 
        { 
           result[first_field] = result[first_field] || [];
           result[first_field].push({ ...fields }); 
        }
    
    

    I didn't make any benchmark but I believe using a for loop would be more efficient than anything suggested in this answer as well.

    0 讨论(0)
  • 2020-11-21 05:32

    Here is another solution to it. As requested.

    I want to make a new array of car objects that's grouped by make:

    function groupBy() {
      const key = 'make';
      return cars.reduce((acc, x) => ({
        ...acc,
        [x[key]]: (!acc[x[key]]) ? [{
          model: x.model,
          year: x.year
        }] : [...acc[x[key]], {
          model: x.model,
          year: x.year
        }]
      }), {})
    }
    

    Output:

    console.log('Grouped by make key:',groupBy())
    
    0 讨论(0)
  • 2020-11-21 05:34

    Here is your very own groupBy function which is a generalization of the code from: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore

    function groupBy(xs, f) {
      return xs.reduce((r, v, i, a, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});
    }
    
    const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];
    
    const result = groupBy(cars, (c) => c.make);
    console.log(result);

    0 讨论(0)
  • 2020-11-21 05:34

    Prototype version using ES6 as well. Basically this uses the reduce function to pass in an accumulator and current item, which then uses this to build your "grouped" arrays based on the passed in key. the inner part of the reduce may look complicated but essentially it is testing to see if the key of the passed in object exists and if it doesn't then create an empty array and append the current item to that newly created array otherwise using the spread operator pass in all the objects of the current key array and append current item. Hope this helps someone!.

    Array.prototype.groupBy = function(k) {
      return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
    };
    
    const projs = [
      {
        project: "A",
        timeTake: 2,
        desc: "this is a description"
      },
      {
        project: "B",
        timeTake: 4,
        desc: "this is a description"
      },
      {
        project: "A",
        timeTake: 12,
        desc: "this is a description"
      },
      {
        project: "B",
        timeTake: 45,
        desc: "this is a description"
      }
    ];
    
    console.log(projs.groupBy("project"));
    
    0 讨论(0)
  • 2020-11-21 05:34

    I made a benchmark to test the performance of each solution that don't use external libraries.

    JSBen.ch

    The reduce() option, posted by @Nina Scholz seems to be the optimal one.

    0 讨论(0)
  • 2020-11-21 05:37

    Grouped Array of Object in typescript with this:

    groupBy (list: any[], key: string): Map<string, Array<any>> {
        let map = new Map();
        list.map(val=> {
            if(!map.has(val[key])){
                map.set(val[key],list.filter(data => data[key] == val[key]));
            }
        });
        return map;
    });
    
    0 讨论(0)
提交回复
热议问题