
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements