Sorting and find sum of differences for an array using JavaScript

Problem

We need to write a JavaScript function that takes an array of integers, sorts them in descending order, and then calculates the sum of differences between consecutive pairs.

For example, if the array is:

[6, 2, 15]

After sorting in descending order: [15, 6, 2]

The sum of differences would be:

(15 - 6) + (6 - 2) = 9 + 4 = 13

Solution

Here's the implementation that sorts the array and calculates the sum of consecutive differences:

const arr = [6, 2, 15];

const sumDifference = (arr = []) => {
    const descArr = arr.sort((a, b) => b - a);
    
    if (descArr.length <= 1) {
        return 0;
    }
    
    let total = 0;
    for (let i = 0; i < descArr.length - 1; i++) {
        total += (descArr[i] - descArr[i + 1]);
    }
    
    return total;
};

console.log(sumDifference(arr));
13

How It Works

The function follows these steps:

  • Sort in descending order: Uses sort((a, b) => b - a) to arrange elements from largest to smallest
  • Handle edge cases: Returns 0 if array has 1 or fewer elements
  • Calculate differences: Iterates through consecutive pairs and adds their differences

Example with Different Array

const testArray = [10, 3, 8, 1, 5];

console.log("Original array:", testArray);
console.log("Sum of differences:", sumDifference(testArray));

// Let's trace through the calculation
const sorted = [...testArray].sort((a, b) => b - a);
console.log("Sorted array:", sorted);
console.log("Calculations: (10-8) + (8-5) + (5-3) + (3-1) =", 
           (10-8), "+", (8-5), "+", (5-3), "+", (3-1), "=", 
           (10-8) + (8-5) + (5-3) + (3-1));
Original array: [ 10, 3, 8, 1, 5 ]
Sum of differences: 9
Sorted array: [ 10, 8, 5, 3, 1 ]
Calculations: (10-8) + (8-5) + (5-3) + (3-1) = 2 + 3 + 2 + 2 = 9

Key Points

  • The function modifies the original array during sorting. Use [...arr].sort() to preserve the original
  • Returns 0 for arrays with fewer than 2 elements since no differences can be calculated
  • The time complexity is O(n log n) due to sorting, and space complexity is O(1)

Conclusion

This approach efficiently calculates the sum of differences between consecutive elements in a sorted array. The key is sorting in descending order first, then iterating through adjacent pairs to compute their differences.

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

398 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements