Compare 2 lines in alphabetical order for sorting

I am trying to compare 2 lines in alphabetical order for sorting. For example, I want to have a logical check like if('aaaa' < 'ab') . I tried, but this does not give me the correct results, so I assume that this is not the correct syntax. How to do it in jquery or javascript?

+84
javascript jquery
Apr 17 '12 at 20:00
source share
5 answers

Let's look at some test cases - try running the following expressions in the JS console:

 "a" < "b" "aa" < "ab" "aaa" < "aab" 

All return true.

JavaScript compares a string character by character, and "a" precedes "b" in the alphabet β€” hence less.

In your case, it works like this -

1. " a aaa" <" a b"

compares the first two characters "a" - all are equal, allows you to go to the next character.

2. "a a aa" <"a b "

compares the second character "a" with "b" - screams! "a" precedes "b". Returns true.

+101
Apr 17 '12 at 20:05
source share

You say the comparison is for sorting. Then I suggest instead:

 "a".localeCompare("b"); 

It returns -1 , since "a" < "b" , 1 or 0 otherwise, as you need for Array.prototype.sort ()

Keep in mind that sorting is language dependent. For example. in German, Γ€ is a variant of a , so "Γ€".localeCompare("b", "de-DE") returns -1 . In Swedish, Γ€ is one of the last letters in the alphabet, so "Γ€".localeCompare("b", "se-SE") returns 1 .

Without the second localeCompare parameter, the browser locale is used. Which in my experience is never what I want, because then it will be sorted differently than a server that has a fixed locale for all users.

+112
Jan 13 '16 at 23:38
source share

Just remember that string comparisons like "x"> "X" are case sensitive

 "aa" < "ab" //true "aa" < "Ab" //false 

You can use .toLowerCase() for case .toLowerCase() comparisons.

+29
Jul 28 '13 at 7:29
source share

"a".localeCompare("b") should really return -1 , since a sorts before b

http://www.w3schools.com/jsref/jsref_localecompare.asp

+5
Sep 12 '16 at 20:13
source share

Let's say we have an array of objects:

 { name : String } 

then we can sort our array as follows:

 array.sort(function(a, b) { var orderBool = a.name > b.name; return orderBool ? 1 : -1; }); 

Note: be careful with capital letters; you may need to lowercase the string because of your purpose.

+1
Aug 22 '19 at 15:49
source share



All Articles