Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Stefanacef/9e3a8b98b51b8c349b8c82950fb79fa9 to your computer and use it in GitHub Desktop.
Save Stefanacef/9e3a8b98b51b8c349b8c82950fb79fa9 to your computer and use it in GitHub Desktop.
Diagonal Difference | Solution | JavaScript
let arr = [
[-1, 1, -7, -8],
[-10, -8, -5, -2],
[0, 9, 7, -1],
[4, 4, -2, 1],
];
function diagonalDifference(arr) {
// Extraction of the primary diagonal
let left = arr
.map((e, i) => {
return arr[i][i];
})
.reduce((acc, e) => acc + e);
//Extraction of the secondary diagonal.
let right = arr
.map((e, i) => {
return arr[i][arr.length - i - 1];
})
.reduce((acc, e) => acc + e);
//difference
let dif = left - right;
// return absolute difference value.
return Math.abs(dif);
}
console.log(diagonalDifference(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment