Minimum Absolute Difference in an Array

  • + 3 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 ).

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

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