![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements