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

JavaScript数组按t_id分组并计算val1求和的技术实现需求

Solution: Group by t_id, Sum val1, and Handle Division

Got it, let's break down how to solve this problem step by step. First, we need to group the array entries by their t_id value, calculate the total sum of val1 for each group, then address the division part—since the exact division rule wasn't spelled out, I'll cover a few common scenarios you might need.

Step 1: Group by t_id and Sum val1

The most straightforward way to do this in JavaScript is using the reduce() method. We'll convert the string val1 values to numbers first (since your input has them as strings), then build an object where each key is a t_id, and the value holds the sum plus any other relevant fields you might want to keep.

const data = [
  {t_id :"1", val1 : "1" , title:"cash to purchase", unit :"bag"},
  {t_id :"1" ,val1 : "1" , title:"cash to purchase", unit :"bag"},
  {t_id :"1",val1 : "1" , title:"cash to purchase", unit :"bag"},
  {t_id :"2",val1 : "4" , title:"offload", unit :"bag"},
  {t_id :"2",val1 : "5" , title:"onroad", unit :"bag"},
  {t_id :"3", val1 : "5" , title:"Onroad", unit :"bag"},
  {t_id :"3", val1 : "6" , title:"Onroad", unit :"bag"}
];

// Group by t_id and calculate total val1
const groupedTotals = data.reduce((accumulator, currentItem) => {
  // Convert val1 from string to number to avoid string concatenation
  const numericVal = Number(currentItem.val1);
  
  // Initialize the group if it doesn't exist yet
  if (!accumulator[currentItem.t_id]) {
    accumulator[currentItem.t_id] = {
      t_id: currentItem.t_id,
      totalVal1: 0,
      title: currentItem.title, // Keep title if needed
      unit: currentItem.unit    // Keep unit if needed
    };
  }
  
  // Add the current val1 to the group's total
  accumulator[currentItem.t_id].totalVal1 += numericVal;
  return accumulator;
}, {});

// If you need the result as an array instead of an object, use Object.values()
const groupedTotalsArray = Object.values(groupedTotals);
console.log(groupedTotalsArray);

Running this will give you an array of objects where each entry has the t_id, total sum of val1, and the associated title/unit. For your input, the output will look like:

[
  { t_id: '1', totalVal1: 3, title: 'cash to purchase', unit: 'bag' },
  { t_id: '2', totalVal1: 9, title: 'offload', unit: 'bag' },
  { t_id: '3', totalVal1: 11, title: 'Onroad', unit: 'bag' }
]

Step 2: Handle Division (Common Scenarios)

Since the exact division rule wasn't specified, here are a few common use cases you might be aiming for:

Scenario 1: Divide each group's total by a fixed number

If you need to divide every group's totalVal1 by a set value (like 3, for example), you can use map() to update each group:

// Divide each group's total by 3
const fixedDivisionResult = groupedTotalsArray.map(group => ({
  ...group,
  divisionResult: group.totalVal1 / 3
}));

Scenario 2: Divide one group's total by another

If you need to compare groups (e.g., divide the total of t_id=2 by t_id=1), you can access the groups directly from the groupedTotals object:

// Divide t_id=2's total by t_id=1's total
const group1Total = groupedTotals["1"].totalVal1;
const group2Total = groupedTotals["2"].totalVal1;
const crossGroupDivision = group2Total / group1Total; // Will be 9 / 3 = 3

Scenario 3: Divide each item's val1 before summing

If the division should happen per-item before calculating the total, adjust the reduce() step to divide first:

// Divide each val1 by 2, then sum for each group
const groupedSumAfterDivision = data.reduce((acc, item) => {
  const numericVal = Number(item.val1);
  const dividedVal = numericVal / 2; // Replace 2 with your divisor
  
  if (!acc[item.t_id]) {
    acc[item.t_id] = {
      t_id: item.t_id,
      totalVal1: 0,
      title: item.title,
      unit: item.unit
    };
  }
  
  acc[item.t_id].totalVal1 += dividedVal;
  return acc;
}, {});

Pick the scenario that matches your actual requirement, or tweak the code to fit whatever division rule you need!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:51:59