Mick White wrote:
[...]
You'll have to roll your own sort function:
[...]
A good start Mick that got me thinking. I can't believe JavaScript
doesn't have a generic sort that works on alpha-numeric strings. So I
had a hack at your code and came up with what's below. My contribution
to the world is to kick off a generic sort function.
Whether numbers sort ahead of non-numbers can be modified to suit by
making all comparisons using ASCII codes or by changing the charCodeAt
lines slight to add or subtract a constant, or multiply by -1;
My modification of your script handles any format string. To handle
numbers and non-numbers, I change non-numbers to their ASCII code and
compare that to single digits. Not great, but it does sort OK - caveat
below.
If the sort runs out of characters to compare, it should put the
shortest one ahead of the longest. Different browsers require a
different return value: Safari needs -1, Firefox needs 0. I don't know
how to discriminate using feature detection - or should I be returning
something else?
Also, this causes a difference in the sort order for different browsers
(arggghh).
I got it this far, over to the gurus. An improvement would be to have
two sorts: sortAsNum() and sortAsChar().
Test results (all on Mac):
Safari: fine
Camino: fine
Firefox: need to change return -1 to return 0
IE 5.2: fails
Netscape: need to change return -1 to return 0
Opera: Sometimes needs -1, sometimes 0 depending on whether some
entries start with alphas or not.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD><title>Sort play</title>
<script type="text/javascript">
function shortestOf(a,b) {
return (a.length <= b.length)? a.length:b.length;
}
function bobSort(a,b){
var z = shortestOf(a,b);
for (var i=0; i<shortestOf(a,b); i++) {
var c = a.split('')
;
var d = b.split('');
if ( c != d ) {
c = (isNaN(c))? c.charCodeAt(0):c;
d = (isNaN(d))? d.charCodeAt(0):d;
var x = c-d;
return c - d;
}
}
return -1;
}
function saySort(inp) {
var p = inp.split('\n');
alert(p);
alert(p.sort(bobSort).join('\n'));
}
</script>
</HEAD>
<BODY>
<form action="">
<textarea cols="40" rows="20" name="stuff">04-273-0005
040-272-0001
040-272-0003
040-272-0001
04a-2y2-00c0
04-273-0001
04a-222-00a0
04a-222-00b0
04a-222-00b1
04z-2x2-00a0
04a-2x2-00a0
04a-2y2-00a0
04a-2y2-00c0
04a-2y2-00b0
04a
0ba-cc2&&8##y2-00b0
</textarea>
<input type="button" value="saySort()" onclick="
saySort(this.form.stuff.value);
"> <input type="reset">
</form>
</BODY>
</HTML>