Skip to content

Instantly share code, notes, and snippets.

View Pvag's full-sized avatar
🌴
exploring

Paolo Vagnini Pvag

🌴
exploring
  • freelancer
View GitHub Profile
@Pvag
Pvag / matrixToArray.js
Last active February 7, 2019 23:09
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]