Last active
February 7, 2019 23:09
-
-
Save Pvag/9190b9c5defa43b744cad62be9f8c544 to your computer and use it in GitHub Desktop.
An example on how to sum elements by column in a 2D matrix. An exercise, using array iterators (i.e. reduce and map).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const nums = [1, 10, 100]; | |
| const matrix = [nums, nums, nums]; // each nums array represents a row in matrix | |
| // reduce accumulates, for each row, the sum of elements in the same column | |
| const columnsSum = matrix.reduce( (accumulated, actual) => { | |
| // this sums element by element, the accumulated array and the actual row | |
| return accumulated.map( (n, index) => { | |
| return n + actual[index]; | |
| }); | |
| }); | |
| console.log(colSums); // prints [3, 30, 300] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment