Javascript Equivalent to the PHP natsort()

This Javascript function is performs in the same way as the PHP function natsort($array). The function returns the array sorted in a natural way, as humans would naturally sort a list.

// return the array sorted just like the php function natsort($array)

function natsort($a) {
    return $array.sort(function (a,b) {
        if ( isNaN(a) && isNaN(b) ) {
            if (a<=b) { return false; } else { return true; }
        }        
        if (isNaN(a)) { return true; }
        if (isNaN(b)) { return false; }
        return a-b;
    });
}

Example:

Javascript:
$array = [5,100,7,4,6,3,8,20,9,10,2,0,1,"natural","sorting","javascript"];
$array = natsort($array); // calls the Javascript function defined above

Produces the result: 
0,1,2,3,4,5,6,7,8,9,10,20,100,"javascript","natural","sorting"

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use