/    Sign up×
Community /Pin to ProfileBookmark

Sort question regarding CASE of array elements

In the following demo script all works fine.
My question concerns the display order of the string array
when I try to ignore the CASE of the elements.

My question is highlighted in the script when you run it. ?

[code]
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″ />
<title>Sort Demos </title>

<style>
p { background-color: lime; }
b { background-color: orange; font-size: 1.4em; }
</style>

</head>
<body>
<h2>Sorting Numbers – sort() &amp; sort().reverse()</h2>
<pre id=”sort1″></pre>

<h2>Sorting Numbers – sort(functions())</h2>
<pre id=”sort2″></pre>

<h2>Sorting Strings – sort() &amp; sort().reverse() </h2>
<pre id=”sort3″></pre>

<pre id=”debug”></pre>

<script>
var nary = [1,10,100,200,20,2,5,50,1000],
sary = [‘Bee’,’bee’,’a’,’A’,’bonnett’,’Cat’,’cat’,’dog’,’zebra’,’Zebra’,’cash’,’fish’,’bird’,’devil’],
ary = [], str = ”, bkwd = ”, frwd = ”;

function d(IDS) { return document.getElementById(IDS); }

ary = [].concat(nary);
str = ‘orig: ‘+nary+’nnBkwd: ‘+nary.sort().reverse()+’nnFwrd: ‘+nary.sort();
d(‘sort1’).innerHTML = str;

ary = [].concat(nary);
bkwd = nary.sort( function(a,b){ return b-a; } ).join(‘,’);
frwd = nary.sort( function(a,b){ return a-b; } ).join(‘,’);
str = ‘orig: ‘+nary + ‘nnBkwd: ‘+bkwd + ‘nnFrwd: ‘+frwd;
d(‘sort2’).innerHTML = str;

ary = [].concat(sary);
bkwd = ary.sort().reverse().join(‘,’);
frwd = ary.sort().join(‘,’);
str = ‘orig: ‘+ sary + ‘nnBkwd: ‘+bkwd + ‘nnFrwd: ‘+frwd;
d(‘sort3’).innerHTML = str;

str = ‘<p>All of above work as expected</p><hr>n’;

ary = [].concat(sary);
bkwd = ary.sort( function(a,b) { return (a.toLowerCase() < b.toLowerCase()); } ).join(‘,’);
frwd = ary.sort( function(a,b) { return (a.toLowerCase() > b.toLowerCase()); } ).join(‘,’);

str += ‘<h2>Sorting Strings – sort(functions(toLowerCase())) – sort ignoring case</h2>’;
str += ‘Note order of duplicates in arrayn’;
str += ‘orig: ‘+ sary + ‘nnBkwd: ‘+bkwd + ‘nnFrwd: ‘+frwd;

[COLOR=”#FF0000″]
str += “<p>nWhy is ‘a’ before ‘A’ but ‘Bee’ is before ‘bee'”;
str += “nAND ‘Cat’ is before ‘cat’ but ‘zebra’ is before ‘Zebra'”
str += “nusing the <b>SAME</b> sort functions()n”;
str += “nShould A B C and Z be consistent before or after a b c and z?n </p>”;
[/COLOR]
document.getElementById(‘debug’).innerHTML = str;

</script>

</body>
</html>
[/code]

to post a comment
JavaScript

6 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumNov 26.2017 — Interesting issue, it is discussed here, e. g.:

https://en.wikipedia.org/wiki/Category:Stable_sorts

As you are converting the strings to lower before comparing, "Cat" gets equal to "cat" and if the sorting is stable, the original sequence is kept.

This resource

https://wiki.selfhtml.org/wiki/JavaScript/Objekte/Array/sort

says that most modern browsers implement a stable sort.
Copy linkTweet thisAlerts:
@JMRKERauthorNov 26.2017 — Thank you 'Sempervivum'.

I would never have associated 'stable' with 'sort' in a search!

Would I need to do a second comparison within the function to check the order WITHOUT case

in order to achieve what I expected (consistency)? I'll see if I can modify this script.
Copy linkTweet thisAlerts:
@SempervivumNov 26.2017 — Yes, recommend doing a second comparison using the original strings if the first comparison results in equality. Something like this:
function(a,b) {
if (a.toLowerCase() &lt; b.toLowerCase()) return -1;
else if (a.toLowerCase() &lt; b.toLowerCase()) return 1;
else return (b - a);
}
(untested you will shurely get it running.)
Copy linkTweet thisAlerts:
@JMRKERauthorNov 26.2017 — I'll try your function next.

Here's what I came up with while I was away.
<i>
</i>frwd = ary.sort(
function(A,B) {
a = A.toLowerCase(); b = B.toLowerCase();
if (a == b) { return (A &gt; B); }
else { return (a &gt; b); }
}
).join(',');


Tested and it seems to work.

Here are the substitute functions to use in post #1
<i>
</i>/* WORKS */
bkwd = ary.sort(
function(A,B) {
var a = A.toLowerCase(), b = B.toLowerCase();
if (a == b) { return (A &lt; B); }
else { return (a &lt; b); }
}
).join(',');
frwd = ary.sort(
function(A,B) {
var a = A.toLowerCase(), b = B.toLowerCase();
if (a == b) { return (A &gt; B); }
else { return (a &gt; b); }
}
).join(',');
/* */
Copy linkTweet thisAlerts:
@rootNov 27.2017 — When sorting, you only need pass the [B]compare function [COLOR="#000080"]function(a,b){ return test-elements; }[/COLOR][/B] as a parameter of the [B].sort()[/B] method.

I have tried your code and its not working in my browser, so I wrote a function and it does not work, so I opened up a file I know works and it didn't work... for some reason, chrome is not playing by the rules... Only last week the browser refused to accept letters A,X and c input from the keyboard...

Your main sort compare functions

[B]function(a,b){ return a-b;}

function(a,b){ return b-a;}

function(a,b){ return a>b;}

function(a,b){ return a<b;}[/B]


and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort should tell you what you need to know.
Copy linkTweet thisAlerts:
@JMRKERauthorNov 28.2017 — Well, I think I understand the problem with communications on this subject.

It appears that the SAME script runs on FireFox and Chrome browsers produce DIFFERENT results.

Save script to local file and run from both browsers.

Chrome seems to not work correctly.

And I can not even test it in the Edge browser

as I am unable to open a local file at all.

I tried to attach images of the output of the code used in BOTH browsers,

but for some reason I am unable to attach an image file of the different screens.

<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt; HTML5 page &lt;/title&gt;
&lt;style type="text/css"&gt;
.p { background-color: pink; }
.g { background-color: lime; }

.fbox-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
background-color: white;
}
.fbox-item {
width: 150px; /* min-width: 125px; min-height: 150px; /* */
border: 1px solid blue; margin: 0.25em;
}
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt; Sort Examples - All in-place sorts &lt;/h1&gt;

&lt;h2&gt; Number array Sorts &lt;/h2&gt;
&lt;div class="fbox-container"&gt;
&lt;pre class="fbox-item p" id="origNums"&gt;&lt;/pre&gt;
&lt;pre class="fbox-item" id="sortNums"&gt;&lt;/pre&gt;
&lt;pre class="fbox-item g" id="specSortNums"&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2&gt; String array Sorts &lt;/h2&gt;
&lt;div class="fbox-container"&gt;
&lt;pre class="fbox-item p" id="origStrs"&gt;&lt;/pre&gt;
&lt;pre class="fbox-item" id="sortStrs"&gt;&lt;/pre&gt;
&lt;pre class="fbox-item g" id="specSortStrs"&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;script&gt;

function numSortA( a, b) { // number sort
return ( a - b );
}
function numSortD( a, b) { // number sort
return ( b - a );
}

function strSortA( a, b) { // string sort
return ( a &gt; b );
}
function strSortD( a, b) { // string sort
return ( a &lt; b );
}

function charOrdA(A, B) { // ascending sort
var a = A.toLowerCase(), b = B.toLowerCase();
if (a == b) { return (A &gt; B); }
else { return (a &gt; b); }
}
function charOrdD(A, B) { // decending sort
var a = A.toLowerCase(), b = B.toLowerCase();
if (a == b) { return (A &lt; B); }
else { return (a &lt; b); }
}
function doc(IDS) { return document.getElementById(IDS); }


var nary = [ 1000,1,10,100,50,5,250,20,2 ];

var str = "Orig: n&lt;br&gt;" + nary.join('&lt;br&gt;');
doc('origNums').innerHTML = str;

<i> </i>str = "n.sort()&lt;br&gt;"+ [ 1000,1,10,100,50,5,250,20,2 ].sort().join('&lt;br&gt;');
doc('sortNums').innerHTML = str;

<i> </i>str = "n.sort(func)&lt;br&gt;"+nary.sort(numSortA).join('&lt;br&gt;');
doc('specSortNums').innerHTML = str;



var sary = ['Bee','bee','a','A','bonnet','Cat',
// '500','25','5', // NOTE order of number displays in strings
'cat','dog','zebra','Zebra','cash','fish','bird','devil'];

<i> </i>str = "Orig: s&lt;br&gt;" + sary.join('&lt;br&gt;');
doc('origStrs').innerHTML = str;

<i> </i>sary = ['Bee','bee','a','A','bonnet','Cat',
// '500','25','5', // NOTE order of number displays in strings
'cat','dog','zebra','Zebra','cash','fish','bird','devil'].sort();
str = "s.sort()&lt;br&gt;"+sary.join('&lt;br&gt;');
doc('sortStrs').innerHTML = str;

<i> </i>sary = sary.sort(charOrdA);
<i> </i>str = "s.sort(func)&lt;br&gt;"+sary.join('&lt;br&gt;');
doc('specSortStrs').innerHTML = str;

&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;


Checked the BING browser and it appears to sort correctly (same as the FireFox browser).
×

Success!

Help @JMRKER spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...