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

如何返回匹配object.date并对object.value求和的对象数组?

Solution: Filter Objects by Date and Sum Their Values

Let's walk through how to solve this problem with clear, reusable code. I'll use JavaScript for examples (since it's common for this type of data handling), but the core logic applies to most programming languages.

Step 1: Define Sample Data

First, let's set up some example data to work with:

const data = [
  { date: '2024-05-01', value: 10 },
  { date: '2024-05-01', value: 20 },
  { date: '2024-05-02', value: 15 },
  { date: '2024-05-01', value: 5 }
];

Step 2: Filter Objects by Target Date

Use the filter() method to extract all objects where the date property matches your target. This creates a new array with only the matching items:

const targetDate = '2024-05-01';
const matchedItems = data.filter(item => item.date === targetDate);

This works by iterating over each item in the original array and keeping only those where item.date exactly equals targetDate.

Step 3: Sum the value Properties

Next, use the reduce() method to calculate the total of all value properties in the filtered array:

const totalValue = matchedItems.reduce((runningTotal, item) => runningTotal + item.value, 0);
  • The reduce() function takes a callback and an initial value (0 here).
  • For each item in matchedItems, it adds the item's value to the running total.
  • If there are no matched items, it returns 0 instead of throwing an error.

Combine into a Reusable Function

To make this easier to use across your codebase, wrap the logic in a function that returns both the matched array and the total sum:

function getMatchedItemsWithSum(data, targetDate) {
  // Filter matching items
  const matchedItems = data.filter(item => item.date === targetDate);
  // Calculate total value
  const totalValue = matchedItems.reduce((sum, item) => sum + item.value, 0);
  // Return both results
  return { matchedItems, totalValue };
}

// Usage example
const result = getMatchedItemsWithSum(data, '2024-05-01');
console.log('Matched Items:', result.matchedItems);
console.log('Total Value:', result.totalValue); // Outputs 35

Handling Edge Cases

  • Date objects instead of strings: If your date properties are JavaScript Date objects, normalize them to strings before comparing (e.g., item.date.toISOString().split('T')[0] === targetDate to get the YYYY-MM-DD format).
  • Non-numeric value: Add a check to ensure item.value is a number (e.g., sum + Number(item.value) to avoid accidental string concatenation).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:14:24