假设我们有一个像这样的对象数组-
const arr = [ { 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" } ];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组作为第一个参数。
我们的目的是能够基于多个或一个单独的属性(由第二个,第三个参数表示)对给定数组进行分组。
因此,如果我们进行groupby阶段,我们应该收到-
const output = [ { Phase: "Phase 1", Value: 50 }, { Phase: "Phase 2", Value: 130 } ];
如果我们对阶段/步骤进行分组,我们应该收到-
const output = [ { 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 } ];
为此的代码将是-
const arr = [ { 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" } ]; const groupBy = (array, groups, valueKey) => { const map = new Map; groups = [].concat(groups); return array.reduce((acc, val) => { groups.reduce((accu, value, ind, { length }) => { let child; if (accu.has(val[value])) { return accu.get(val[value]); }; if (ind + 1 === length) { child = Object .assign(...groups.map(value => ({ [value]: val[value] })), { [valueKey]: 0 }); acc.push(child); } else { child = new Map; }; accu.set(val[value], child); return child; }, map)[valueKey] += +val[valueKey]; return acc; }, []); }; console.log(groupBy(arr, 'Phase', 'Value')); console.log(groupBy(arr, ['Phase', 'Step'], 'Value'));
输出结果
控制台中的输出将是-
[ { Phase: 'Phase 1', Value: 50 }, { Phase: 'Phase 2', Value: 130 } ] [ { 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 } ]