How to solve the problem: return the sum of the primary and secondary diagonals of a square matrix?

  • 0
    Design a JavaScript implementation of sumUpDiagonals () to return the sum of the primary and secondary diagonals of a square matrix.
    var matrixExample = [
        [ 1, 2, 3, 4 ],
    	[ 4, 5, 6, 5 ],
    	[ 7, 8, 9, 7 ],
    	[ 7, 8, 9, 7 ]
    ];
    function sumUpDiagonals(matrix) {
       // ...
    }
    console.log(sumUpDiagonals(matrixExample));
    JavaScript Anonymous, Apr 11, 2019

  • 1 Answers
  • 0
    const sumDiagonals = matrix =>
    matrix.reduce((acc, n, i) => {
    acc.principal += n[i];
    acc.secondary += n[n.length - i - 1];
    return acc;
    }, {
    principal: 0,
    secondary: 0,
    });
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!