/    Sign up×
Community /Pin to ProfileBookmark

issue array.sort()

Ok, I’m trying to sort an array using .sort() function. It has some strange behaviour. The following are numbers my script gave before being sorted, and after. For some reason they are not always being sorted. check it out:

[quote]

CASE 1
Pre-Sort:
16
11
11
16
14
6
Post-Sort:
11
11
14
16
16
6

CASE 2
Pre-Sort:
16
10
9
15
15
13
Post-Sort:
10
13
15
15
16
9

[/quote]

Strange isn’t it? If any can help I’d really appreciate it, I’m at a total loss. If there’s any information i’m not including that would help let me know.

to post a comment
JavaScript

7 Comments(s)

Copy linkTweet thisAlerts:
@mudeltaJan 14.2007 — the function sorts them as strings.

Are you sure you've put them in the array as numbers?
Copy linkTweet thisAlerts:
@mrhooJan 14.2007 — Give sort a function to work with

myArray=myArray.sort(function(a, b){ return a-b})

This expression will convert string 'numbers' to numbers,

but will fail if the array contains strings that can't evaluate to numbers.
Copy linkTweet thisAlerts:
@PadonakJan 14.2007 — <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Sorting Array elements</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<style type="text/css">
<!--
body{
margin: 0px 0px 0px 0px;
color: #000;
background-color: #F8F8FF;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
}
a:link,a:active,a:visited{
color: #708090;
background-color: transparent;
text-decoration: none;
font-weight: bold;
letter-spacing: normal;
}
a:hover{
color: #000;
background-color: transparent;
text-decoration: none;
font-weight: bold;
letter-spacing: 2px;
}
#content{
width: 100%;
height: 100%;
text-align: center;
position: absolute;
top: 0px;
left: 0px;
}
-->
</style>
<script language="JavaScript" type="text/javascript">
<!--
var arr_1 = new Array("16","11","11","16","14","6");
var arr_2 = new Array("16","10","9","15","15","13");

function makePreview(){
var cont = document.getElementById("content");
cont.innerHTML = "<br /><br /><br />Case 1 (pre-sort): ";
for(var i = 0; i < arr_1.length; i++){
if(i < arr_1.length - 1){cont.innerHTML += "   " + arr_1[i];}
else{cont.innerHTML += "   " + arr_1[i] + "<br /><br /><a href='#null' onclick='makeSorted(1)'>sort this one</a>";}
}
cont.innerHTML += "<br /><br /><hr style='width:200px;' /><br />Case 2 (pre-sort): ";
for(var j = 0; j < arr_2.length; j++){
if(j < arr_2.length - 1){cont.innerHTML += "   " + arr_2[j];}
else{cont.innerHTML += "   " + arr_2[j] + "<br /><br /><a href='#null' onclick='makeSorted(2)'>sort this one</a>";}
}
for(var k = 0; k < document.links.length; k++){document.links[k].onfocus = function(){this.blur();}}
}

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

function makeSorted(n){
if(!document.getElementById("divDemo"))
var field = document.createElement("div");
field.setAttribute("id","divDemo");
field.style.position = "absolute";
field.style.top = 0 + "px";
field.style.left = 0 + "px";
field.style.color = "Navy";
field.style.backgroundColor = "#f6f6ee";
field.style.border = "2px outset #fff";
field.style.padding = "50px 50px 50px 50px";
field.style.zIndex = "10";
field.style.cursor = "pointer";
field.style.textAlign = "center";
field.title = "Close";
field.innerHTML = "The Array <span style='color:Crimson;background-color:transparent;font-weight:900'>arr_" + n + "</span> after being sorted:<br /><br /><span style='color:Darkgreen;background-color:transparent;font-weight:900;'>" + eval("arr_" + n + ".sort(doCompare).join(' ')") + "</span>";
document.body.appendChild(field);
field.style.top = document.body.clientHeight*0.5 - field.offsetHeight/2 + "px";
field.style.left = document.body.clientWidth*0.5 - field.offsetWidth/2 + "px";
document.getElementById("divDemo").onclick = function(){document.body.removeChild(document.getElementById("divDemo"))}
}

//-->
</script>
</head>
<body onload="makePreview()">
<div id="content"></div>
</body>
</html>


enjoy :-)
Copy linkTweet thisAlerts:
@mishkinauthorJan 14.2007 — 
mrhoo


Registered User Join Date: Feb 2006

Posts: 700

Give sort a function to work with

myArray=myArray.sort(function(a, b){ return a-b})

This expression will convert string 'numbers' to numbers,

but will fail if the array contains strings that can't evaluate to numbers.
[/quote]

OK! This worked, but I don't understand why or how. Can you explain how function(a,b){return a-b} works and why that fixes this issue? SO far as I see there are no parameters sent for a and b... I find this puzzling.
Copy linkTweet thisAlerts:
@mishkinauthorJan 14.2007 — Oh and Padonak, that was pretty impressive. I think you used a similar method, I still don't understand why

function(a,b){return a-b} fixes this, what it does, or why it works.
Copy linkTweet thisAlerts:
@mrhooJan 14.2007 — the array sort function, called with no arguments, returns the result of comparing strings alphabetically.

But a computer does not assign the number 1 to 'A'.

'A' is coded with the number 65, the computer code for the capital A.

The capital letters A-Z have codes ranging from 65 to 90, and the lowercase letters are from 97 to 122.

The computer sorts 'alphabetically' by the values of these character codes.

The default sorting of ['a','atom','Zero'] would be Zero,a, atom, since the capitals have smaller codes than lower case.

To sort an array of strings alphabetically, without regard for case you can enforce upper or lower case on the arguments of the sort function.

A.sort(function(m, n){

a = m.toLowerCase();

b = n.toLowerCase();

if (a == b) return 0;

else return a > b ? 1 : -1;

})

Digits in strings have codes too-from 48 (0) to 57(9),

but when you handle digits as strings they have the properties of strings-

think of the digits as letters that come before 'A'.

'10' is sorted before '11' but also before '6', since the letter '1' (49) has a lower code than '6' (54).

Telling the sort function to return the value of a-b forces digits to be treated like numbers. '10'-'6' converts both variables to numbers, and the returned value shifts the 6 to a position before the 10 in the sorted array.

Other printable characters, like '$', '%' and punctuation will also affect the sort position of a string of text according to each character's position in the ascii alphabet.
Copy linkTweet thisAlerts:
@mishkinauthorJan 15.2007 — thanks you not only cleared up my issue, but taught me something too. ^_^
×

Success!

Help @mishkin 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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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