如何返回匹配object.date并对object.value求和的对象数组?
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 (0here). - For each item in
matchedItems, it adds the item'svalueto the running total. - If there are no matched items, it returns
0instead 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
dateproperties are JavaScriptDateobjects, normalize them to strings before comparing (e.g.,item.date.toISOString().split('T')[0] === targetDateto get the YYYY-MM-DD format). - Non-numeric
value: Add a check to ensureitem.valueis a number (e.g.,sum + Number(item.value)to avoid accidental string concatenation).
内容的提问来源于stack exchange,提问作者Vinicius Zomer

