Sort Array and Find Sum of Differences Using JavaScript



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
Updated on: 2021-04-21T07:00:27+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements