0

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("");
3
  • 1
    a - b is NaN when a and b are non-numeric strings. What are you trying to achieve? Commented Aug 4, 2018 at 0:15
  • return a.sort((a,b) => a > b ? 1 : -1).join(""); should do it Commented Aug 4, 2018 at 0:24
  • @Xufox to return the list of alpha characters in the array in order, like if i do var array = ['c','d','a'] then array.sort(), it returns ['a',''b','c']...i was wondering why when adding the arguments, it doesn't achieve the same thing Commented Aug 4, 2018 at 16:50

3 Answers 3

3

Try using localeCompare:

var a = str.split("")
return a.sort((a, b) => a.localeCompare(b)).join("");

Docs on localeCompare here

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

thanks , that works...just trying to understand that though. Can you explain what that is doing?
@user10108817 a < b ? -1 : 1 simply returns -1 iff a < b and 1 iff a >= b. The sort method expects a number to be returned: if negative, a goes before b, if positive a goes after b. But this conditional expression isn’t semantically perfect, since it’s missing the 0 case, when a and b are equal. That’s why you should really use a.localeCompare(b) instead.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.