Published: 2015-10-13
Updated: 2016-10-14
Web: http://fritzthecat-blog.blogspot.com/2015/10/js-natural-sort-order.html
Here is a port of the natural-sort-order to JavaScript (as an example that JS implementations can also result in readable code :-)
It is directly derived from the Java code of my latest Blog article.
The area below is for trying out the natural sort order. Enter names in the text-area, each in a single line, then press "Sort" to see the sorted result. I've already provided an example list.
You find the JS code working here in the following.
JavaScript provides a
sort()
function on arrays. This sorts alphabetically, no matter whether it is an array of numbers or an array of strings. But as optional argument you can pass a compare-function, this is a function that receives two parameters and is expected to return an integer being ...
Here is an example:
var array = [ 4, 2, 6, 5, 3, 12, 9 ];
var comparator = function(a, b) {
return a - b;
};
array.sort(comparator);
// yields [ 2, 3, 4, 5, 6, 9, 12 ]
Using the JS sort() implementation I just need to provide the comparator
function. For a discussion how natural sorting works please refer to my latest Java Blogs. Wherever it was possible I tried to keep identifiers and objects like they were in the Java code.
By passing one or two booleans to function newNaturalSortComparator()
you could determine whether the comparator ignores upper/lower case or spaces.
1 |
"use strict"; |
Use this like the following:
array.sort(newNaturalSortComparator());
Here is another usage example, actually representing a test.
1 |
(function() { |
ɔ⃝ Fritz Ritzberger, 2015-10-13