Sorting and find sum of differences for an array using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of integers. Our function should sum the differences between consecutive pairs in the array in descending order.

For example − If the array is −

[6, 2, 15]

Then the output should be −

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

Example

Following is the code −

 Live Demo

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));

Output

13
raja
Published on 21-Apr-2021 10:27:30
Advertisements