I wish to compare two strings in javascript. I am using localeCompare method but the output is not as expected
116457 < 3085
false
"116457" < "3085"
true
"116457".localeCompare("3085")
-1
Output in second and third case is not as expected.
I know it sorts in Lexicographical order but still I am having trouble understanding why is it so and how should I overcome this.
Any help would be appreciated.
ponury-kostek
8,0835 gold badges27 silver badges33 bronze badges
asked Jul 11, 2019 at 11:57
user3807691
1,3242 gold badges11 silver badges33 bronze badges
2 Answers 2
If you want to compare them without converting them to numbers, you can set numeric: true in the options parameter
console.log(
"116457".localeCompare("3085", undefined, { numeric: true })
)
console.log(
"116457".localeCompare("3085")
)
answered Jul 11, 2019 at 12:10
adiga
35.4k9 gold badges66 silver badges88 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
If 116457 were a word, it would come before 3085 in a dictionary.
Consider a dictionary with
- "applicative" (a long word starting with "a", c.f. a long digit string starting with "1")
- "copy" (a short word starting with "c", c.f. a shorter digit string starting with "3").
answered Jul 11, 2019 at 11:59
AKX
171k17 gold badges149 silver badges230 bronze badges
8 Comments
user3807691
Okay. Makes sense.
user3807691
But how do I overcome this? (I don't want to convert it to a number)
Jonas Wilms
Convert it to a number? "I don't want to" ... and why?
user3807691
I basically "can't" cast it using parseInt(str) or Number(str) as in the scenario I am handling, it doesn't always gets integers. There are cases I get strings as well. Example : "c-116457" and "c-3085"
jmrk
Well, if you have complex strings where various substrings have specific meaning, then you'll have to write your own comparator function that takes all of that into acount. It may be more efficient to represent your data differently, e.g. as objects with a bunch of properties rather than as a string.
|
lang-js
"1"comes before"3", so any String starting with"1"comes before any other string starting with"3". You say you know this but have trouble understanding why. Would you agree that"a" < "c"?parseInt(str)?