473,796 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sort() a string by a number within the string?

Hi all,

I have an array of strings. For example...

[0] = "entry1 first entry";
[1] = "entry2 second entry";
[2] = "entry3 third entry";
etc...

How can I sort this array by the number after "entry"?

David

Sep 15 '05 #1
9 3562
I should have stated that the array may become mixed when some processing in
the script is changed. For example..

[0] = "entry1 first entry";
[1] = "entry3 third entry";
[2] = "entry2 second entry";
etc...

So I need to straighten it out, sort() it, to be in numerical order by the
number after the word "entry" so that the end result is like this..

[0] = "entry1 first entry";
[1] = "entry2 second entry";
[2] = "entry3 third entry";
etc...

David


"David" <ri***@dd.com > wrote in message
news:sDiWe.1230 3$YI6.11468@trn ddc05...
Hi all,

I have an array of strings. For example...

[0] = "entry1 first entry";
[1] = "entry2 second entry";
[2] = "entry3 third entry";
etc...

How can I sort this array by the number after "entry"?

David

Sep 15 '05 #2


David wrote:
I should have stated that the array may become mixed when some processing in
the script is changed. For example..

[0] = "entry1 first entry";
[1] = "entry3 third entry";
[2] = "entry2 second entry";


An array object has a sort method to which you can pass your own
comparison function if needed that compares what you want to compare e.g.

var a = new Array();
a[0] = "entry1 first entry";
a[1] = "entry3 third entry";
a[2] = "entry2 second entry";

var result = a.join('|');

a.sort(function (el1, el2) {
var pattern = /^entry(\d+)/g;
var n1, n2;
pattern.lastInd ex = 0;
var match1 = pattern.exec(el 1);
if (match1) {
n1 = Number(match1[1]);
}
pattern.lastInd ex = 0;
var match2 = pattern.exec(el 2);
if (match2) {
n2 = Number(match2[1]);
}
if (typeof n1 != 'undefined' && typeof n2 != 'undefined') {
return n1 - n2;
}
else {
// no numbers found
// could throw an error
return -1;
}
});

result += '\r\n\r\n' + a.join('|');

alert(result);
Documentation is here:
<http://developer.mozil la.org/en/docs/Core_JavaScript _1.5_Reference: Global_Objects: Array:sort>

--

Martin Honnen
http://JavaScript.FAQTs.com/
Sep 15 '05 #3

"Martin Honnen" wrote:
An array object has a sort method to which you can pass your own
comparison function if needed that compares what you want to compare e.g.

var a = new Array();
a[0] = "entry1 first entry";
a[1] = "entry3 third entry";
a[2] = "entry2 second entry";

var result = a.join('|');

a.sort(function (el1, el2) {
var pattern = /^entry(\d+)/g;
var n1, n2;
pattern.lastInd ex = 0;
var match1 = pattern.exec(el 1);
if (match1) {
n1 = Number(match1[1]);
}
pattern.lastInd ex = 0;
var match2 = pattern.exec(el 2);
if (match2) {
n2 = Number(match2[1]);
}
if (typeof n1 != 'undefined' && typeof n2 != 'undefined') {
return n1 - n2;
}
else {
// no numbers found
// could throw an error
return -1;
}
});

result += '\r\n\r\n' + a.join('|');

alert(result);
Documentation is here:
<http://developer.mozil la.org/en/docs/Core_JavaScript _1.5_Reference: Global_Objects: Array:sort>

--

Martin Honnen
http://JavaScript.FAQTs.com/

Thanks Martin, that worked quite nicely :-)

David



Sep 15 '05 #4
David wrote:
I have an array of strings. For example...

[0] = "entry1 first entry";
[1] = "entry2 second entry";
[2] = "entry3 third entry";
etc...

How can I sort this array by the number after "entry"?


stringArray=
["entry1 first entry","entry2 second entry","entry3 third entry"]
function davidSort(a,b){
return a.split(" ")[0].replace(/[^\d]/g,"")-
b.split(" ")[0].replace(/[^\d]/g,"");
}
alert(stringArr ay.sort(davidSo rt).join("\n"))

Mick
Sep 15 '05 #5

"Mick White" wrote:
stringArray=
["entry1 first entry","entry2 second entry","entry3 third entry"]
function davidSort(a,b){
return a.split(" ")[0].replace(/[^\d]/g,"")-
b.split(" ")[0].replace(/[^\d]/g,"");
}
alert(stringArr ay.sort(davidSo rt).join("\n"))

Mick

Very elegant and simple. Thanks Mick, it works great.

David
Sep 15 '05 #6
JRS: In article <OXkWe.25286$8h 6.11450@trnddc0 9>, dated Thu, 15 Sep
2005 20:37:02, seen in news:comp.lang. javascript, David <ri***@dd.com >
posted :

"Mick White" wrote:
stringArray=
["entry1 first entry","entry2 second entry","entry3 third entry"]
function davidSort(a,b){
return a.split(" ")[0].replace(/[^\d]/g,"")-
b.split(" ")[0].replace(/[^\d]/g,"");
}
alert(stringArr ay.sort(davidSo rt).join("\n"))

Mick

Very elegant and simple. Thanks Mick, it works great.

Like Martin Honnen's method, it will be unnecessarily show for large
arrays. The expected number of calls of davidSort is greater than o(N)
for an N-element array, and each call performs two non-trivial
manoeuvres.

For efficiency, do a first pass of o(N) which converts each element to
something with the sort key also at the front, do a default (string)
sort o(>N), then strip the key taking o(N). The default comparison
will, I expect, be quicker than using the fastest possible sort
function.
The OP did not unambiguously specify the task : he wrote "number" which
sometimes means "digit" and sometimes "[sign]digit(s)" etc.

You and Martin have, I think, both assumed "number" to mean "string of
decimal digits", which is probably what the OP meant. Neither of you, I
suspect, handle the general case of a number in any form S acceptable to
Number(S).

David, please trim your quotes : see newsgroup FAQ.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Sep 16 '05 #7
Dr John Stockton wrote:
JRS: In article <OXkWe.25286$8h 6.11450@trnddc0 9>, dated Thu, 15 Sep
2005 20:37:02, seen in news:comp.lang. javascript, David <ri***@dd.com >
posted :
"Mick White" wrote:

stringArra y=
["entry1 first entry","entry2 second entry","entry3 third entry"]
function davidSort(a,b){
return a.split(" ")[0].replace(/[^\d]/g,"")-
b.split(" ")[0].replace(/[^\d]/g,"");
}
alert(string Array.sort(davi dSort).join("\n "))

Mick

Very elegant and simple. Thanks Mick, it works great.


Like Martin Honnen's method, it will be unnecessarily show for large
arrays. The expected number of calls of davidSort is greater than o(N)
for an N-element array, and each call performs two non-trivial
manoeuvres.

For efficiency, do a first pass of o(N) which converts each element to
something with the sort key also at the front, do a default (string)
sort o(>N), then strip the key taking o(N). The default comparison
will, I expect, be quicker than using the fastest possible sort
function.


The point of my reply was that he needs to extract from the object that
portion of which he wants to compare. I'm not quite following what
you're saying, I'd love to see a sample.
Of course, the ideal solution is to create the array object correctly in
the first place.


The OP did not unambiguously specify the task : he wrote "number" which
sometimes means "digit" and sometimes "[sign]digit(s)" etc.
Trivial to do, though "entry-1" is unlikely.
You and Martin have, I think, both assumed "number" to mean "string of
decimal digits", which is probably what the OP meant. Neither of you, I
suspect, handle the general case of a number in any form S acceptable to
Number(S).


Yes I did
Mick

Sep 16 '05 #8
JRS: In article <WI************ *******@twister .nyroc.rr.com>, dated
Fri, 16 Sep 2005 21:23:02, seen in news:comp.lang. javascript, Mick White
<mw***********@ rochester.rr.co m> posted :
Dr John Stockton wrote:
Like Martin Honnen's method, it will be unnecessarily show for large
arrays. The expected number of calls of davidSort is greater than o(N)
for an N-element array, and each call performs two non-trivial
manoeuvres.

For efficiency, do a first pass of o(N) which converts each element to
something with the sort key also at the front, do a default (string)
sort o(>N), then strip the key taking o(N). The default comparison
will, I expect, be quicker than using the fastest possible sort
function.


The point of my reply was that he needs to extract from the object that
portion of which he wants to compare.


In fact, one does not *need* to *extract* it.

I'm not quite following what
you're saying, I'd love to see a sample.


Let T be a string such as "entry1 first entry" matching the first
RegExp:
T = T.replace(/^(\D*)(\d+)/, "00000$2$1$ 2")
T = T.replace(/^(.*)(\d{6})/, "$2")
The combination of those adds the value of the first "number" part, as a
SIX-digit string, to the front of T, now "000001entr y1 first entry".
There may be better ways.

If the elements of the array are all treated as T there is, the array
can now be sorted by the default sort, and the original elements can
easily be recovered by substringing.

For this to be worthwhile, the array must be sufficiently large, and
that can only be determined by test since it depends on the browser and
script coding.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Sep 17 '05 #9
>> The OP did not unambiguously specify the task : he wrote "number" which
sometimes means "digit" and sometimes "[sign]digit(s)" etc. You and Martin have, I think, both assumed "number" to mean "string of
decimal digits", which is probably what the OP meant. Neither of you, I
suspect, handle the general case of a number in any form S acceptable to
Number(S).

Mick is correct and his solution worked just fine. By number I did mean that
I wanted to sort by the decimal digit or numeral.

Thank you all for your helpful input.

David
Sep 20 '05 #10

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

Similar topics

2
1498
by: Fawke101 | last post by:
Hi there, I have a JS/ASP application that sorts a SQL populated table. This works great, and sorts the data fine, apart from my currency columns. It wants to read the data as text as far as i can gather. Ths data in ASP looks like this - <% =formatcurrency(RS("income"),2)%> I have tried changing this to a number (formatnumber) and hard coding a £ sign, yet it still wants to read the data as text, rather than numerical?
3
2980
by: Ali Chambers | last post by:
Hi, I have a bit of a problem with a sort procedure I need to do. I have a list of items in a listbox, eg:- 2.3%<A other text here> -4%<B other text here> 10%<C other text here> -9.3%<D other text here> 22%<E other text here>
2
1354
by: seaofcrisis | last post by:
In MSSQL, is there a way to count the number of instances of a substring within a string, so that I can sort by that? For example: table tst contains one column: tst_data if tst_data = "the man with the plan" I'd want a function that counts the occurances of "the"
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";
3
14614
by: andrew | last post by:
Hi: I am already using TreeMap to massage records in my export file such that each record has a unique key combination ( LastName + FirstName + Member Key) . Thus I am sorting the records by the unique key. I also have a Date String Field in my record ( ie "30-Apr-2005" ). I want to create a unique key combination of ( LastName + FirstName + Member Key + Date). Can you please tell me what are the steps I need to do to sort the Date
1
2694
by: Gunjan Garg | last post by:
Hello All, I am working to create a generic datagrid which accepts a datasource(ListData - This is our own datatype) and depending on the calling program customizes itself for sorting, paginantion or accepting the add and remove item events. What i am observing is that none of the vents are happening... (Sort, page, or item). I am sure I am missing something basic here... Need help... Thanks much
21
3226
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...
48
4492
by: Alex Chudnovsky | last post by:
I have come across with what appears to be a significant performance bug in ..NET 2.0 ArrayList.Sort method when compared with Array.Sort on the same data. Same data on the same CPU gets sorted a lot faster with both methods using .NET 1.1, that's why I am pretty sure its a (rather serious) bug. Below you can find C# test case that should allow you to reproduce this error, to run it you will need to put 2 data files into current directory...
6
4062
by: shana07 | last post by:
Phew, I have problem..How to sort number in my files..I have these in my input files...: I need to sort the line in array from 12, 64, 8, 128 etc. 3 12 4 64 7 8 10 128 ... I just wanna sort and number out them : 1 8 2 12
0
9673
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
9524
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
10449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10168
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
6785
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
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5568
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.