# Alternating sum of elements of a two-dimensional array using JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## 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 −

Live Demo

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