You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现可复用函数:从传入数组接收多变量并按指定列聚合求和

Solution for Grouping by Arbitrary Columns & Summing Specified Values in JavaScript

Got it, let's adjust this function to support grouping by any number of columns while keeping the output structure consistent with your original example. Let's break down how to solve each of your three questions:

1. Generating a Group Key for Arbitrary-Length objParams

Instead of hardcoding indexes like a[0] and a[1], we can iterate over the objParams array to pull the corresponding values from each current element, then join them with a separator (like |) to create a unique key for each group. This works no matter how long objParams is:

const key = objParams.map(idx => cur[idx]).join('|');

This ensures every combination of the specified columns gets a distinct key.

2. Replicating the Original Logic for Any Group Parameters

We don't need to declare specific variables from objParams—instead, we just check if our accumulator already has an entry for the generated key. If not, we create a copy of the current element (to avoid mutating the original array) and add it to the accumulator. If it does exist, we simply update the target column's value:

if (!acc[key]) {
  acc[key] = [...cur]; // Create a shallow copy of the current row
} else {
  acc[key][v] += cur[v]; // Sum the values in the specified column
}

Using a shallow copy ([...cur]) is crucial here—it prevents us from accidentally modifying the original input array when we update the summed value.

3. Handling the Target Column (v) Position Correctly

Instead of hardcoding the column index (like [1] in the original function), we just use the v parameter directly to access the correct position in the array. This works regardless of where the numeric column is located in your input rows.


Full Modified Function

Here's the updated function that addresses all three issues:

const inputObj = [ 
  ['Anna', 10, 'Monday'], 
  ['Anna', 15, 'Wednesday'], 
  ['Beatrice', 8, 'Monday'], 
  ['Beatrice', 11, 'Wednesday'], 
  ['Anna', 4, 'Wednesday'], 
  ['Beatrice', 5, 'Monday'], 
  ['Beatrice', 16, 'Monday'] 
];

// Expected output matches your original example
const expectedOutput = [ 
  ['Anna', 10, 'Monday'], 
  ['Anna', 19, 'Wednesday'], 
  ['Beatrice', 29, 'Monday'], 
  ['Beatrice', 11, 'Wednesday'] 
];

const someFunction = (obj, valueCol, groupCols) => {
  const result = obj.reduce((acc, cur) => {
    // Generate unique key from all specified group columns
    const groupKey = groupCols.map(idx => cur[idx]).join('|');
    
    if (!acc[groupKey]) {
      // Initialize group with a copy of the current row
      acc[groupKey] = [...cur];
    } else {
      // Sum the values in the target column
      acc[groupKey][valueCol] += cur[valueCol];
    }
    
    return acc;
  }, {});
  
  // Convert the accumulator object back to an array of rows
  return Object.values(result);
};

// Test with original parameters
console.log(someFunction(inputObj, 1, [0, 2])); 
// Output matches expectedOutput

// Test with a longer group parameter array (example with an extra column)
const extendedInput = inputObj.map(row => [...row, 'Morning']);
console.log(someFunction(extendedInput, 1, [0, 2, 3]));
// Groups by name, day, and time, sums the numeric column

内容的提问来源于stack exchange,提问作者Viet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:06:32