/    Sign up×
Community /Pin to ProfileBookmark

Sorting an array…

How do i use the .sort(); methode with an array to make it so that the elements inside are sorted from least to greatest?… they are all numbers from 2 through 14.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@ExuroJun 25.2003 — Here's a little something I whipped up:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var nums = new Array();
nums = [2,11,4,7,3,14,5,12,10,9,13]

function sizeSort(a, b)
{
if(a < b)
return -1
if(a > b)
return 1
return 0
}

document.write(nums.sort(sizeSort))
// -->
</SCRIPT>
</HEAD>
</HTML>


And when you look at that in the browser it gives you this:

2,3,4,5,7,9,10,11,12,13,14

What I did was included a "compare function" for the sort method. What it does is tells the method how to sort the items in the array. If you want to know more you can read about it here:

http://www.devguru.com/Technologies/ecmascript/quickref/Sort.html

Hope that helped!
Copy linkTweet thisAlerts:
@GopinathJun 25.2003 — var arr1=new Array("a1","b2","F6","D4","E5","C3")

arr1.sort()

for(var int_count=0; int_count<arr1.length; int_count++)

{

alert(arr1[int_count]);

}
Copy linkTweet thisAlerts:
@GreelmoauthorJun 26.2003 — THANKS GUYS!
×

Success!

Help @Greelmo 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.4,
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,
)...