# JavaScript Coding Challenge #6

If you love arrays as much as I do, this post is for you!

Feedback is highly appreciated!

2 Likes

Did I miss something? Wouldnβt it be faster and easier with one loop?

``````function calculateDiagonals(matrix){
var n = matrix.length;
var diag1 = 0;
var diag2 = 0;

for(var i=0; i<n; i++){
diag1 += matrix[i][i];
diag2 += matrix[i][n-i-1];
}
return Math.abs(diag1 - diag2);
}``````
1 Like

Perfect @ksjazzguitar! That is indeed faster!

Thank you for the tip Kevin! Here is a little follow up on the sixth challenge:

Hope you donβt mind I used your solution

As I lay awake in bed last night, it also occurred to me that since (a1 + b1 + β¦) - (a2 + b2 + β¦) is the same as (a1 - a2) + (b1 - b2) + β¦ then we can save a further step by just summing the differences of the pairs instead of summing them individually and then taking their differences. Itβs a small time and memory saver, but it is a little better.

``````function calculateDiagonals(matrix){
var n = matrix.length;
var sumDiff = 0;

for(var i=0; i<n; i++){
sumDiff += matrix[i][i] - matrix[i][n-i-1];
}
return Math.abs(sumDiff);
}``````
2 Likes

Very nice! You are very good at this!