user10108817
user10108817

Reputation: 285

javascript ES6 sorting

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

Answers (3)

Steven Spungin
Steven Spungin

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

Dylan
Dylan

Reputation: 343

Try using localeCompare:

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

Docs on localeCompare here

Upvotes: 3

James Skirving
James Skirving

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

Related Questions