We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

JavaScript version that I like and feel is readable and clean.

functionminimumAbsoluteDifference(arr){// Sortarr.sort();letminDiff;// Loop through the consecutive pairs, if 0 return, else set min difffor(leti=0;i<arr.length;i++){letabsDiff=Math.abs(arr[i+1]-arr[i]);if(!minDiff||absDiff<minDiff)minDiff=absDiff;if(minDiff===0)return0;}returnminDiff;}

For others reading this solution I just want to comment on using arr.sort() in JS since this has burned me before.

By default, Javascript's Array.prototype.sort will sort elements in lexicographical order, which means sorting [2, 4, 30] will convert the integers to strings and produce [2, 30, 4] (since '3' comes before '4'). To properly sort integers a custom compare function should be passed in. I.e. arr.sort( ( a, b ) => a - b ).

The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Somehow none of the test cases triggered this exact scenario and the posted solution indeed passes all tests, but feel free to experiment with various inputs on your own, e.g. [2, 4, 30] (should return 2, but would return 26 using the default sort).

## Minimum Absolute Difference in an Array

You are viewing a single comment's thread. Return to all comments →

JavaScript version that I like and feel is readable and clean.

For others reading this solution I just want to comment on using arr.sort() in JS since this has burned me before.

By default, Javascript's Array.prototype.sort will sort elements in

lexicographical order, which means sorting [2, 4, 30] will convert the integers to strings and produce [2, 30, 4] (since '3' comes before '4'). To properly sort integers a custom compare function should be passed in. I.e. arr.sort( ( a, b ) => a - b ).MDN Reference

Somehow none of the test cases triggered this exact scenario and the posted solution indeed passes all tests, but feel free to experiment with various inputs on your own, e.g. [2, 4, 30] (should return 2, but would return 26 using the default sort).

This is a great callout.