
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Calculate Subtraction of diagonals-summations in a two-dimensional matrix using JavaScript
Suppose, we have a square matrix represented by a 2-D array in JavaScript like this −
const arr = [ [1, 3, 5], [3, 5, 7], [2, 4, 2] ];
We are required to write a JavaScript function that takes in one such array.
The function should return the difference between the sum of elements present at the diagonals of the matrix.
Like for the above matrix, the calculations will be −
|(1+5+2) - (5+5+2)| |8 - 12| 4
Example
Following is the code −
const arr = [ [1, 3, 5], [3, 5, 7], [2, 4, 2] ]; const diagonalDiff = arr => { let sum = 0; for (let i = 0, l = arr.length; i < l; i++){ sum += arr[i][l - i - 1] - arr[i][i]; }; return Math.abs(sum); } console.log(diagonalDiff(arr));
Output
This will produce the following output on console −
4
- Related Articles
- Interchange Diagonals of Matrix using Python
- Computing sums of diagonals of a matrix using Python
- JavaScript subtraction of two float values?
- Alternating sum of elements of a two-dimensional array using JavaScript
- C++ Program to Add Two Matrix Using Multi-dimensional Arrays
- C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays
- Java Program to Add Two Matrix Using Multi-Dimensional Arrays
- Swift Program to Add Two Matrix Using Multi-dimensional Arrays
- Swift Program to Subtract Two Matrix Using Multi-dimensional Arrays
- Golang Program to Add Two Matrix Using Multi-dimensional Arrays
- Addition and Subtraction of Matrix using pthreads in C/C++
- PHP program to calculate the repeated subtraction of two numbers
- Transpose of a two-dimensional array - JavaScript
- JavaScript Program to Efficiently compute sums of diagonals of a matrix
- Row-wise common elements in two diagonals of a square matrix in C++

Advertisements