473,788 Members | 2,725 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array sort function sorts on chars not numbers ... help ! how to sort numbers

My question is ... How do I sort an Array on numeric, not character values ?

In the example below, after sorting the contents are 1,10,2,3 .

How do I get the contents to be 1,2,3,10 ?

Thanks,

em

<html>
<head>
<script>
function TestSort() {
var nums = new Array(0);
nums[0] = 1;
nums[1] = 2;
nums[2] = 10;
nums[3] = 3;
nums.sort();
for ( i = 0 ; i < 4 ; i++ ) {
alert(nums[i]);
}
return true;
}
</script>
</head>
<body bgcolor="lightb lue">
<input type="button" onclick="TestSo rt();" value="Click Me">
</body>
</html>
Jul 23 '05 #1
5 1667
"GIMME" <gi************ *******@yahoo.c om> wrote in message
news:3f******** *************** ***@posting.goo gle.com...
My question is ... How do I sort an Array on numeric, not character values ?
In the example below, after sorting the contents are 1,10,2,3 .

How do I get the contents to be 1,2,3,10 ?

Thanks,

em

<html>
<head>
<script>
function TestSort() {
var nums = new Array(0);
nums[0] = 1;
nums[1] = 2;
nums[2] = 10;
nums[3] = 3;
nums.sort();
for ( i = 0 ; i < 4 ; i++ ) {
alert(nums[i]);
}
return true;
}
</script>
</head>
<body bgcolor="lightb lue">
<input type="button" onclick="TestSo rt();" value="Click Me">
</body>
</html>


Here's a solution; watch for word-wrap.
<html>
<head>
<title>sortnum. htm</title>
<script type="text/javascript">
function TestSort() {
var nums = new Array(0);
nums[0] = 1;
nums[1] = 2;
nums[2] = 10;
nums[3] = 3;
nums.sort();
for (var i=0; i<nums.length; i++) {
nums[i] = (10000 + nums[i]);
}
nums.sort();
var numx = "";
for (var j=0; j<nums.length; j++) {
numx += (nums[j] - 10000) + "\n";
}
alert(numx);
}
</script>
</head>
<body onload="TestSor t()">
</body>
</html>

Jul 23 '05 #2
Ivo
"GIMME" wrote
My question is ... How do I sort an Array on numeric, not character values ?
In the example below, after sorting the contents are 1,10,2,3 .

How do I get the contents to be 1,2,3,10 ?
Two steps. See inserted lines:
<html>
<head>
<script>
function TestSort() {
var nums = new Array(0);
nums[0] = 1;
nums[1] = 2;
nums[2] = 10;
nums[3] = 3;
nums.sort();
1. Make that:
nums.sort(sortn umeric);
for ( i = 0 ; i < 4 ; i++ ) {
alert(nums[i]);
}
return true;
}
2. And add:
function sortnumeric(a,b ){ return parseFloat(a)-parseFloat(b); }
</script>
</head>
<body bgcolor="lightb lue">
<input type="button" onclick="TestSo rt();" value="Click Me">
</body>
</html>


HTH
Ivo
Jul 23 '05 #3
Lee
GIMME said:

My question is ... How do I sort an Array on numeric, not character values ?


It's hard to believe that you could find any documentation on Array.sort()
that doesn't include an example of how to sort numerically.
There's one at this link:

http://tinyurl.com/4ohf4

<http://devedge.netscap e.com/library/manuals/2000/javascript/1.5/reference/array.html#1196 882>

Jul 23 '05 #4
JRS: In article <40************ *********@news. wanadoo.nl>, dated Thu,
22 Jul 2004 02:44:28, seen in news:comp.lang. javascript, Ivo
<no@thank.you > posted :
"GIMME" wrote
My question is ... How do I sort an Array on numeric, not character values

That might be FAQ-worthy; I've seen it quite a few times. There's
obvious generalisation to other types of sort, e.g. dates using getTime
or valueOf, both of which should be quick.

2. And add:
function sortnumeric(a,b ){ return parseFloat(a)-parseFloat(b); }


That requires, for each of the ~ o(N ln N) comparisons, two conversions
of number to string and two conversions of string to number. Only
subtraction is needed.

I can believe that adding a large constant to each number could be
quicker, for large sorts, since it avoids calling a user-defined
function.

Someone tell ECMA to add a numericSort method to anything that has a
sort method. The chief benefit would be that, eventually, it would
appear in documentation, help files, and books; and it should be a
little quicker.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #5
GIMME wrote:
My question is ... How do I sort an Array on numeric, not
character values ?


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

var a = new Array(...);
a.sort(numSort) ;

It is described in detail in the Client-side JavaScript 1.3+
References, if you would have cared to RTFFAQ/RTFM prior to
posting you would have known.
PointedEars
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
3269
by: Dr John Stockton | last post by:
Q1 : Given an array such as might have been generated by var A = is there a highly effective way of reducing it to - i.e. removing the undefineds and shifting the rest down? A.sort().slice(0,n) // would do it, but sorts; and the number
7
4019
by: Christopher Jeris | last post by:
I am relatively new to JavaScript, though not to programming, and I'm having trouble finding the idiomatic JS solution to the following problem. I have a table with (say) fields f1, f2, f3. I do a database query and what I wind up with is a structure Q of arrays: Q.f1 is field f1 in row n, Q.f1.length == Q.f2.length == Q.f3.length is the record count of the query. (This representation is of course backwards, but that's what...
7
3266
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) CType(local4, Short) = CType(src, Short)
15
3215
by: David | last post by:
sorry for the last post, itchy fingers. I'm having a bit of difficulty sorting images named in sequential numerical order. Here are the image names and how I need them sorted. image1.jpg image2.jpg image3.jpg image4.jpg image5.jpg
19
2633
by: David | last post by:
Hi all, A while back I asked how to sort an array of strings which would have numerals and I wanted to put them in sequential numerical order. For example: myArray = "file1"; myArray = "file2"; myArray = "file3"; myArray = "file4"; myArray = "file5";
21
3224
by: yeti349 | last post by:
Hi, I'm using the following code to retrieve data from an xml file and populate a javascript array. The data is then displayed in html table form. I would like to then be able to sort by each column. Once the array elements are split, what is the best way to sort them? Thank you. //populate data object with data from xml file. //Data is a comma delimited list of values var jsData = new Array(); jsData = {lib: "#field...
2
1350
by: almurph | last post by:
Folks, I have an array of chars nad would like to remove any repeating terms. Any ideas as how to do this? Thanks, Al.
24
3462
by: Michael | last post by:
Hi, I am trying to pass a function an array of strings, but I am having trouble getting the indexing to index the strings rather than the individual characters of one of the strings. I have declared an array as: char *stringArray = {"one","two","three","a"}; When I pass the array using:
49
3175
by: vfunc | last post by:
If I have a large array 10,000+ elements then how do I reserve memory for this ? Currently I get a segmentation fault. Dynamic reservation is good, but allowing a chunk for the program is an acceptable alternative.
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10173
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.