Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
/*
 * Natural Sort algorithm for Javascript
 *
 * Author: Lauri Rooden
 *
 * code source on https://github.com/litejs/natural-compare-lite
 *
 */
 var naturalSort = function(a, b) {
    if (a != b) for (var i, ca, cb = 1, ia = 0, ib = 0; cb;) {
        ca = a.charCodeAt(ia++) || 0;
        cb = b.charCodeAt(ib++) || 0;
        if (ca < 58 && ca > 47 && cb < 58 && cb > 47) {
            for (i = ia; ca = a.charCodeAt(ia), ca < 58 && ca > 47; ia++);
            ca = (a.slice(i - 1, ia) | 0) + 1;
            for (i = ib; cb = b.charCodeAt(ib), cb < 58 && cb > 47; ib++);
            cb = (b.slice(i - 1, ib) | 0) + 1;
        }
        if (ca != cb) return (ca < cb) ? -1 : 1;
    }
    return 0;
};
/*
 * Sample usages, using javascript's native array's .sort() method
 *
 * see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
 */
var stringArray = [' ciao', 'ciao', 'hello', 'hellothere', 'hello there'];
/* non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.),  */
var stringArrayWithNonAsciiChars = ['réservé', 'réserve', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
var numericStringArray = ['80', '9', '700'];
var stringAlphanumericalOne = [' ','1','a'];
var stringAlphanumericalTwo = ['img ','img1','imga', 'imgz'];
var stringAlphanumericalThree = ['img 99','img199','imga99', 'imgz99'];
var stringAlphanumericalFour = ['img12.png','img10.png','img2.png','img1.png']; 
console.log( stringArray.sort(naturalSort) );
console.log( stringArrayWithNonAsciiChars.sort(naturalSort) );
console.log( numericStringArray.sort(naturalSort) );
console.log( stringAlphanumericalOne.sort(naturalSort) );
/* in the call below it fails! order should be ["img ", "img1", "imga", "imgz"] */
console.log( stringAlphanumericalTwo.sort(naturalSort) );
/* in the call below it fails! order should be ["img 99", "img199", "imga99", "imgz99"] */
console.log( stringAlphanumericalThree.sort(naturalSort) );
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers