

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Sorting and find sum of differences for an array 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
- Related Questions & Answers
- Sorting an array of objects by an array JavaScript
- Sorting an array of literals using quick sort in JavaScript
- Sorting an array of binary values - JavaScript
- Alternative sorting of an array in JavaScript
- Sorting only a part of an array JavaScript
- Sorting an array that contains the value of some weights using JavaScript
- Sorting an array of objects by property values - JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Algorithm for sorting array of numbers into sets in JavaScript
- Sorting Array without using sort() in JavaScript
- Find the difference of largest and the smallest number in an array without sorting it in JavaScript
- Uneven sorting of array in JavaScript
- Implementing partial sum over an array using JavaScript
Advertisements