JavaScript嵌套数组求和与动态百分比计算问题求助
Hey there! I see you're working with a 3-level nested array and need to transform the innermost arrays into objects with their total sum and a percentage relative to 400. The issue you're hitting with map makes sense—since your array has three layers, you need to use nested map calls to reach the innermost elements properly.
Here's a straightforward solution that matches your expected output:
Step-by-Step Explanation
- Traverse the outer array: Use
mapto go through each middle-level array. - Traverse each middle array: Another
mapto access every innermost number array. - Calculate the total sum: Use
reduceto add up all numbers in the innermost array. - Compute the dynamic percentage: Divide the total by 400, multiply by 100, and format it to show either a whole number (like 100%) or two decimal places (like 99.75%).
Complete Code Example
// Helper function to process the nested array const processNestedArray = (arr) => { return arr.map(middleArray => { // Iterate over each innermost array in the middle layer return middleArray.map(innerNumbers => { // Calculate total sum of the innermost array const total = innerNumbers.reduce((accumulator, num) => accumulator + num, 0); // Compute percentage relative to 400 const percentageValue = (total / 400) * 100; // Format percentage: remove .00 for whole numbers, keep two decimals otherwise const average = percentageValue % 1 === 0 ? `${percentageValue}%` : `${percentageValue.toFixed(2)}%`; return { total, average }; }); }); }; // Your original array const originalArr = [ [ [100, 100, 100, 100], [100, 100, 100, 100], [100, 100, 98, 100], [100, 100, 100, 100], ], [ [100, 100, 100, 99], [100, 100, 100, 100], [100, 100, 100, 100], [100, 100, 100, 100], ] ]; // Get the processed result const processedArr = processNestedArray(originalArr); console.log(processedArr);
Output
This will produce exactly the structure you're looking for:
[ [ { total: 400, average: '100%' }, { total: 400, average: '100%' }, { total: 398, average: '99.50%' }, { total: 400, average: '100%' }, ], [ { total: 399, average: '99.75%' }, { total: 400, average: '100%' }, { total: 400, average: '100%' }, { total: 400, average: '100%' }, ] ]
Note: I noticed your example showed 99.99% for the sum 398, but mathematically 398/400 = 99.5%—the code above uses the correct calculation. If you need to round differently (like always rounding to two decimals even if it's a .5), you can adjust the toFixed logic accordingly.
内容的提问来源于stack exchange,提问作者Rio

