简体   繁体   中英

In a loop that results in several arrays, how to return an array with the sum of all of them

I have an array of strings that, after a lot of effort, I have managed to turn into several arrays with a loop. So right now, the loop is giving me something like:

[4,5,6,7,8]
[4,5,6,7,8],[1,2,3,4,5]
[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]

If I place the return lower in the code, I get: [[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]]

What I need is the vertical sum of these arrays, so in this case it'd be: [27,40,53,66,80]

So far, I'm usign '.push'. Also, console.log gives me this answer but return results in 'undefined'. Any help with these two things would be welcome!

----UPDATE----

As someone here suggested, I tried this but it doesn't work entirely:

array=[ [ 1, 2, 4 ], [ 4, 1, 5 ], [ 0, 5, 2 ] ];
let adding=0
const result=[]
for (let i = 0; i < array[0].length; ++i) {
    for (let j = 0; j < array.length; ++j) {
            adding += array[j][i];
            }
            result.push(adding);}
console.log(result)
    ```

The ouput is: [ 5, 13, 24 ] instead of [5,8,11]

1) You can easily achieve the result using map and reduce

 const arr = [ [4, 5, 6, 7, 8], [1, 2, 3, 4, 5], [22, 33, 44, 55, 66], ]; const result = arr[0].map((_, i) => arr.reduce((acc, curr) => acc + curr[i], 0)); console.log(result)

2) Using simple for loops

 const arr = [ [4, 5, 6, 7, 8], [1, 2, 3, 4, 5], [22, 33, 44, 55, 66], ]; const result = []; for (let i = 0; i < arr[0].length; ++i) { let sum = 0; for (let j = 0; j < arr.length; ++j) { sum += arr[j][i]; } result.push(sum); } console.log(result);

 let arrays = [ [4,5,6,7,8], [1,2,3,4,5], [22,33,44,55,66], ]; let ar_sum = []; for (let x = 0; x < 5; x++) { let sum = 0; arrays.forEach((array) => { sum += array[x]; }); ar_sum.push(sum); } console.log(ar_sum);

Here's a simple readable version.

Create a new array and gradually fill it up

 const verticalSummation = (nestedArray) => { if (nestedArray.length == 0) return []; const result = new Array(nestedArray[0].length).fill(0); for (let i = 0; i < result.length; i++) { for (const arr of nestedArray) { result[i] += arr[i]; } } return result; } console.log(verticalSummation([[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM