Skip to content

Instantly share code, notes, and snippets.

@Pvag
Last active February 7, 2019 23:09
Show Gist options
  • Select an option

  • Save Pvag/9190b9c5defa43b744cad62be9f8c544 to your computer and use it in GitHub Desktop.

Select an option

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).
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