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: Brian Huisman
 * Based on: Dave Koelle's work www.davekoelle.com/alphanum.html
 *
 * code source on http://www.davekoelle.com/files/alphanum.js
 *
 */
 var naturalSort = function (a, b) {
  function chunkify(t) {
    var tz = new Array();
    var x = 0, y = -1, n = 0, i, j;
    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        tz[++y] = "";
        n = m;
      }
      tz[y] += j;
    }
    return tz;
  }
  var aa = chunkify(a.toLowerCase());
  var bb = chunkify(b.toLowerCase());
  for (x = 0; aa[x] && bb[x]; x++) {
    if (aa[x] !== bb[x]) {
      var c = Number(aa[x]), d = Number(bb[x]);
      if (c == aa[x] && d == bb[x]) {
        return c - d;
      } else return (aa[x] > bb[x]) ? 1 : -1;
    }
  }
  return aa.length - bb.length;
};
/*
 * 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