
- 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
Alternating sum of elements of a two-dimensional array using JavaScript
Problem
We are required to write a JavaScript function that takes in a 2-Dimensional array of m X n order of numbers containing the same number of rows and columns.
For this array, our function should count and return the following sum−
$\sum_{i=1}^m \sum_{j=1}^n (-1)^{i+j}a_{ij}$
Example
Following is the code −
const arr = [ [4, 6, 3], [1, 8, 7], [2, 5, 9] ]; const alternateSum = (arr = []) => { let sum = 0; for(let i = 0; i < arr.length; i++){ for(let j = 0; j < arr[i].length; j++){ const multiplier = (i + j) % 2 === 0 ? 1 : -1; sum += (multiplier * arr[i][j]); }; }; return sum; }; console.log(alternateSum(arr));
Output
7
- Related Articles
- Transpose of a two-dimensional array - JavaScript
- Split one-dimensional array into two-dimensional array JavaScript
- Absolute sum of array elements - JavaScript
- Thrice sum of elements of array - JavaScript
- Shift the bits of array elements of a Two-Dimensional array to the left in Numpy
- Shift the bits of array elements of a Two-Dimensional array to the right in Numpy
- Sum of distinct elements of an array - JavaScript
- Return the sum of two consecutive elements from the original array in JavaScript
- Sum of distinct elements of an array in JavaScript
- How to create a two dimensional array in JavaScript?
- Calculate Subtraction of diagonals-summations in a two-dimensional matrix using JavaScript
- Maximum sum of n consecutive elements of array in JavaScript
- Finding sum of alternative elements of the array in JavaScript
- Find sum of two array elements index wise in Java
- Sum of all the non-repeating elements of an array JavaScript

Advertisements