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.
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 →
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).