如何在Node.js中实现动态多数组对应元素求和并返回单数组?
Absolutely! This is totally doable, and there are clean, flexible approaches to handle this—even when the number of sub-arrays changes on the fly (as long as all sub-arrays share the same length, which you’ve noted is the case here).
Core Concept
The main idea is straightforward: for each index position (like the first element, second element, etc.), add up the values from every sub-array at that position, then collect all those sums into your final result array.
Python Implementation
Python has built-in tools that make this a breeze:
values = [[10,20,30,40,0],[0,0,5,10,15],[3,0,0,0,10]] result = [sum(column) for column in zip(*values)] print(result) # Output: [13, 20, 35, 50, 25]
Let’s break this down step by step:
zip(*values)takes your list of arrays and groups elements by their index. So you get tuples like(10, 0, 3)(first elements of all arrays),(20, 0, 0)(second elements), and so on.sum(column)calculates the total for each of these grouped tuples.- The list comprehension wraps it all up into the result array you need.
JavaScript Implementation
If you’re working in JavaScript, you can use reduce() and map() to get the same result:
const values = [[10,20,30,40,0],[0,0,5,10,15],[3,0,0,0,10]]; const result = values.reduce((accumulator, currentArray) => { return currentArray.map((num, index) => accumulator[index] + num); }); console.log(result); // Output: [13, 20, 35, 50, 25]
Here’s how this works:
reduce()starts with the first array as the initialaccumulator(the running total array).- For each subsequent array,
map()goes through each element, adding it to the corresponding position in the accumulator. - By the end of the loop, the accumulator holds the sum of all matching elements across every sub-array.
Both methods work perfectly even if you add or remove sub-arrays later—no need to tweak the core code, as long as all sub-arrays keep the same length.
内容的提问来源于stack exchange,提问作者Aravind

