如何不用多分支判断实现rawData数组中coincell值的分组求和?
Great question! Ditching repetitive if/else branches for a cleaner, maintainable approach is always smart—especially when you’re dealing with a fixed set of categories like your 6 coincell values. Here are two universal JavaScript solutions that work across all standard environments (no niche features required):
Option 1: Use a Mapping Object + forEach (Simple & Readable)
The core idea is to create an object where each key matches one of your coincell values, and the value is the running total for that category. This lets you directly map each row’s coincell to its sum variable without conditionals.
// Step 1: Initialize sums for all 6 coincell types (replace with your actual values) const sumTracker = { "coincell-type-1": 0, "coincell-type-2": 0, "coincell-type-3": 0, "coincell-type-4": 0, "coincell-type-5": 0, "coincell-type-6": 0 }; // Step 2: Iterate over your rawData array rawData.forEach(row => { const currentCoincell = row[0].coincell; // Get the coincell value from the row const valueToAdd = row[1].yourNumericProperty; // Replace with the actual value you're summing from row1 // Only update if the coincell is one of our expected types (avoids unexpected values) if (sumTracker.hasOwnProperty(currentCoincell)) { sumTracker[currentCoincell] += valueToAdd; } }); // Now sumTracker holds the total for each coincell type! console.log(sumTracker["coincell-type-1"]); // Example: total for the first type
Option 2: Use Array.reduce (More Functional Style)
If you prefer a more concise, functional approach, Array.reduce() (supported in all ES5+ environments) lets you compute the sums in a single pass:
// Initialize the starting sums (same as above) const initialSums = { "coincell-type-1": 0, "coincell-type-2": 0, "coincell-type-3": 0, "coincell-type-4": 0, "coincell-type-5": 0, "coincell-type-6": 0 }; // Reduce the rawData array into the final sums object const finalSums = rawData.reduce((acc, row) => { const coincell = row[0].coincell; const addValue = row[1].yourNumericProperty; if (acc.hasOwnProperty(coincell)) { acc[coincell] += addValue; } return acc; }, initialSums); // Access totals directly from finalSums console.log(finalSums["coincell-type-3"]);
Why This Is Better Than if/else Branches:
- Maintainability: If you ever add or remove a coincell type, you just update the initial sums object—no need to edit a long chain of conditionals.
- Readability: The logic is straightforward: map each category to its sum, no nested conditions to parse.
- Safety: The
hasOwnPropertycheck prevents accidental sums for unexpected coincell values (like typos or edge cases).
内容的提问来源于stack exchange,提问作者Jo Gilpo

