search

Home  >  Q&A  >  body text

Best way to group array of objects

What is the most efficient way to group objects in an array?

For example, given this object array:

[ 
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]

I am displaying this information in a table. I want to group by different methods but I want to sum the values.

I'm using Underscore.js for its groupby functionality, which helps a lot but doesn't solve the whole problem because I don't want them to "split" but "merge", more like SQL group by method.

I'm looking to be able to calculate the sum of specific values ​​(if needed).

So if I execute groupby Phase, I expect to receive:

[
    { Phase: "Phase 1", Value: 50 },
    { Phase: "Phase 2", Value: 130 }
]

If I execute groupy Phase / Step, I receive:

[
    { Phase: "Phase 1", Step: "Step 1", Value: 15 },
    { Phase: "Phase 1", Step: "Step 2", Value: 35 },
    { Phase: "Phase 2", Step: "Step 1", Value: 55 },
    { Phase: "Phase 2", Step: "Step 2", Value: 75 }
]

Is there a useful script, or should I stick with Underscore.js and loop through the result objects to calculate the total myself?

P粉348915572P粉348915572440 days ago618

reply all(2)I'll reply

  • P粉933003350

    P粉9330033502023-10-10 22:01:48

    Using ES6 Map object:

    /**
     * @description
     * Takes an Array, and a grouping function,
     * and returns a Map of the array grouped by the grouping function.
     *
     * @param list An array of type V.
     * @param keyGetter A Function that takes the the Array type V as an input, and returns a value of type K.
     *                  K is generally intended to be a property key of V.
     *
     * @returns Map of the array grouped by the grouping function.
     */
    //export function groupBy(list: Array, keyGetter: (input: V) => K): Map> {
    //    const map = new Map>();
    function groupBy(list, keyGetter) {
        const map = new Map();
        list.forEach((item) => {
             const key = keyGetter(item);
             const collection = map.get(key);
             if (!collection) {
                 map.set(key, [item]);
             } else {
                 collection.push(item);
             }
        });
        return map;
    }
    
    
    // example usage
    
    const pets = [
        {type:"Dog", name:"Spot"},
        {type:"Cat", name:"Tiger"},
        {type:"Dog", name:"Rover"}, 
        {type:"Cat", name:"Leo"}
    ];
        
    const grouped = groupBy(pets, pet => pet.type);
        
    console.log(grouped.get("Dog")); // -> [{type:"Dog", name:"Spot"}, {type:"Dog", name:"Rover"}]
    console.log(grouped.get("Cat")); // -> [{type:"Cat", name:"Tiger"}, {type:"Cat", name:"Leo"}]
    
    const odd = Symbol();
    const even = Symbol();
    const numbers = [1,2,3,4,5,6,7];
    
    const oddEven = groupBy(numbers, x => (x % 2 === 1 ? odd : even));
        
    console.log(oddEven.get(odd)); // -> [1,3,5,7]
    console.log(oddEven.get(even)); // -> [2,4,6]

    About the map: https://developer.mozilla.org/en-US /docs/Web/JavaScript/Reference/Global_Objects/Map

    reply
    0
  • P粉681400307

    P粉6814003072023-10-10 09:27:55

    If you want to avoid using an external library, you can simply implement the plain version of groupBy() like this:

    var groupBy = function(xs, key) {
      return xs.reduce(function(rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
      }, {});
    };
    
    console.log(groupBy(['one', 'two', 'three'], 'length'));
    
    // => {"3": ["one", "two"], "5": ["three"]}

    reply
    0
  • Cancelreply