Reputation: 285
When I use only sort()
without arguments, it returns correctly in alphabetical order. When I try to add in arguments like below, it just returns the word in the same order the string was entered in. I'm not entirely sure what I'm doing incorrectly.
var a = str.split("")
return a.sort((a,b) => a-b).join("");
Upvotes: 0
Views: 72
Reputation: 29159
Try this:
var str = 'zyxw'
var a = str.split("")
console.log(a)
var res = a.sort((a,b) => a.localeCompare(b)).join("");
console.log(res)
Upvotes: 0
Reputation: 343
Try using localeCompare
:
var a = str.split("")
return a.sort((a, b) => a.localeCompare(b)).join("");
Upvotes: 3
Reputation: 64
When comparing strings a - b won't work. You can use the ternary logic operator here: a < b ? -1 : 1
Place that expression in the function you pass to sort and that should do the trick.
Upvotes: 0