In Javascript, if I have an array of arrays representing a matrix, say
x = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
];
summing it
You can use recursivity to sum arrays of any dimensions with this function:
function sumRecursiveArray(arr) {
return arr.reduce(function(acc, value) {
return acc + (Array.isArray(value) ? sumRecursiveArray(value) : value);
}, 0);
}
var sum = sumRecursiveArray([[1,1,1],[2,2,2]]);
console.log(sum); // 9