The most efficient way to group object arrays
P粉310754094
P粉310754094 2023-08-21 14:34:06
0
2
578
<p>What is the most efficient way to group objects in an array? </p> <p>For example, given the following array of objects: </p> <pre class="brush:php;toolbar:false;">[ { 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" } ]</pre> <p>I am displaying this information in a table. I want to group by different methods but I want to sum the values. </p> <p>I'm using the groupby function of Underscore.js, which is helpful, but doesn't quite satisfy the need because I don't want to "separate" them but "merge" them, more like SQL's group by method. </p> <p>What I want is to be able to sum specific values ​​if needed. </p> <p>So, if I group by <code>Phase</code>, I want to get: </p> <pre class="brush:php;toolbar:false;">[ { Phase: "Phase 1", Value: 50 }, { Phase: "Phase 2", Value: 130 } ]</pre> <p>If I group by <code>Phase</code> / <code>Step</code>, I want to get: </p> <pre class="brush:php;toolbar:false;">[ { 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 } ]</pre> <p>Is there a useful script that can do this, or should I just keep using Underscore.js and do the summing by looping over the result objects? </p>
P粉310754094
P粉310754094

reply all(2)
P粉029327711

Use ES6 Map object:

/**
 * @description
 * 接受一个类型为V的数组和一个分组函数,返回按照分组函数分组的数组的Map。
 *
 * @param list 类型为V的数组。
 * @param keyGetter 一个函数,接受类型为V的数组作为输入,并返回类型为K的值。
 *                  K通常是V的属性键。
 *
 * @returns 按照分组函数分组的数组的Map。
 */
//export function groupBy<K, V>(list: Array<V>, keyGetter: (input: V) => K): Map<K, Array<V>> {
//    const map = new Map<K, Array<V>>();
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;
}


// 使用示例

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 Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

P粉590428357

If you want to avoid using an external library, you can simply implement a native 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"]}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!