Thursday, December 17, 2020

Array sorting in JavaScript

 REf:

 https://joel.net/custom-array-sort-algorithms-in-javascript



Complex Custom Sorting

I recently had a use case where an API was returning data that looked like this.

// API Response
["1", "10", "2", "BLA", "BLA2", "3"]

The Array contained all String items, but the business wanted the items to display like "1, 2, 3, 10, BLA, BLA2".

That meant, I had to detect when the String was a Number and Sort the "numbers" first and the text after.

As complex as that sounds, the sort algorithm wasn't too bad.

const isNumeric = (num) => !isNaN(num)

const customCompare = (a, b) => {
    if (isNumeric(a) && !isNumeric(b)) return -1
    if (!isNumeric(a) && isNumeric(b)) return 1
    if (isNumeric(a) && isNumeric(b)) return a - b
    return a < b ? -1 : 1
}

// [ '1', '2', '3', '10', 'BLA', 'BLA2' ]



Autoboxing and Unboxing

  Autoboxing  is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper cl...