I want to find the differences between all closest-neigbour pairs and sum them, given the input array is even-length.
I have this code right now but it only gives the minimum difference of one pair. How do I go about to achieve this? So take out the pairs who have already been summed and calculate with the rest of the pairs.
var lowestDiff = Infinity;
arr.sort((a, b) => a - b);
for (var i = 0; i < arr.length - 1; i++) {
lowestDiff = Math.min(lowestDiff, Math.abs(arr[i] - arr[i + 1]));
}
console.log(lowestDiff);
So for example if the input is: [6,2,3,6], output would be: 1 because 6 pairs with 6 and 2 pairs with 3
So essentially i want to pair an element with another element which is closest to them, and get that difference. And sum them.