2013-11-09

Example of JavaScript Sort Method Using Custom Sort Function

Example of JavaScript Sort Method Using Custom Predicate

// array sort example
var aa = ["a1", "a70", "a8", "A2"];

// default sort. element compared as string
aa.sort();
console.log(aa);                // [ 'A2', 'a1', 'a70', 'a8' ]

// sort by comparing as numbers after first char
aa.sort(ff);
console.log(aa);                // [ 'a1', 'A2', 'a8', 'a70' ]

function ff (x,y) {

    var nx = parseInt(x.slice(1)); // remove first char. consider rest as number
    var ny = parseInt(y.slice(1));

    if ( nx < ny ) { return -1; }
    if ( nx > ny ) { return 1; }
    if ( nx == ny ) { return 0; }
}

see more at JavaScript Array Methods