473,326 Members | 2,732 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

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 3535
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.12303$YI6.11468@trnddc05...
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.lastIndex = 0;
var match1 = pattern.exec(el1);
if (match1) {
n1 = Number(match1[1]);
}
pattern.lastIndex = 0;
var match2 = pattern.exec(el2);
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.mozilla.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.lastIndex = 0;
var match1 = pattern.exec(el1);
if (match1) {
n1 = Number(match1[1]);
}
pattern.lastIndex = 0;
var match2 = pattern.exec(el2);
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.mozilla.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(stringArray.sort(davidSort).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(stringArray.sort(davidSort).join("\n"))

Mick

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

David
Sep 15 '05 #6
JRS: In article <OXkWe.25286$8h6.11450@trnddc09>, 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(stringArray.sort(davidSort).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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Sep 16 '05 #7
Dr John Stockton wrote:
JRS: In article <OXkWe.25286$8h6.11450@trnddc09>, 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(stringArray.sort(davidSort).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.com> 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 "000001entry1 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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.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
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...
3
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...
2
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...
19
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 =...
3
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...
1
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,...
21
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...
48
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...
6
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...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.