Calculate the difference between the first and second element of each subarray separately and return the sum of their differences in JavaScript

In JavaScript, we often need to process arrays of subarrays and perform calculations on their elements. This article demonstrates how to calculate the difference between the first and second element of each subarray and return the sum of all differences.

What is an Array of Subarrays?

An array of subarrays (or nested array) is an array that contains other arrays as its elements. Each inner array is called a subarray.

const array = [[1, 2], [4, 5], [7, 8]];
console.log(array[0]);    // First subarray
console.log(array[1][0]); // First element of second subarray
[ 1, 2 ]
4

Problem Logic

To solve this problem, we need to:

  1. Iterate through each subarray
  2. Calculate the difference: subarray[1] - subarray[0]
  3. Sum all the differences

Using Array.reduce() Method

The reduce() method provides an elegant solution by accumulating the sum of differences:

const arr = [[1, 3], [7, 9], [11, 5]]; 

const sum = arr.reduce((acc, subArr) => {  
  const diff = subArr[1] - subArr[0];  
  return acc + diff; 
}, 0);

console.log("Sum of differences:", sum);
Sum of differences: 0

Using a For Loop

A traditional for loop approach offers more explicit control:

const arr = [[1, 3], [7, 9], [11, 5]];
let sum = 0;

for (let i = 0; i < arr.length; i++) {
  const subArr = arr[i];
  const diff = subArr[1] - subArr[0];
  sum += diff;
}

console.log("Sum of differences:", sum);
Sum of differences: 0

Step-by-Step Calculation

Let's trace through the calculation with our example array [[1, 3], [7, 9], [11, 5]]:

const arr = [[1, 3], [7, 9], [11, 5]];

console.log("Subarray 1: [1, 3] ? Difference:", 3 - 1);
console.log("Subarray 2: [7, 9] ? Difference:", 9 - 7);  
console.log("Subarray 3: [11, 5] ? Difference:", 5 - 11);

const totalSum = (3-1) + (9-7) + (5-11);
console.log("Total sum:", totalSum);
Subarray 1: [1, 3] ? Difference: 2
Subarray 2: [7, 9] ? Difference: 2
Subarray 3: [11, 5] ? Difference: -6
Total sum: -2

Comparison of Methods

Method Code Length Readability Performance
reduce() Shorter Functional style O(n)
for loop Longer More explicit O(n)

Time and Space Complexity

Both approaches have:

  • Time Complexity: O(n) where n is the number of subarrays
  • Space Complexity: O(1) for additional variables

Conclusion

Both reduce() and for loop methods effectively calculate the sum of differences between subarray elements. The reduce() method offers a more functional programming approach, while the for loop provides explicit control over the iteration process.

Updated on: 2026-03-15T23:19:00+05:30

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements