0
var test = ['hello', 'Hello']
var arg1 = test[0].split('').sort().join('').toLowerCase();  // ehllo
var arg2 = test[1].split('').sort().join('').toLowerCase();  // hello

Would someone be able to explain why the sort method appears to have no effect on the 2nd element of the test array?

adam.shaleen
  • 993
  • 3
  • 9
  • 20

3 Answers3

8

console.log('H' < 'e', 'H'.charCodeAt(0), 'e'.charCodeAt(0));

Capital letters range from 65 to 90. Lower case letters range from 97 to 122. String comparisons are based on character codes.

Consider being more explicit with your sort by using a custom function.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
4

If you want to ignore case, you should lowercase before sorting:

console.log('Hello'.toLowerCase().split('').sort().join('')); // ehllo
Oriol
  • 274,082
  • 63
  • 437
  • 513
2

This question was answered in StackOverflow before case insensitive sorting in Javascript

'Hello'.split('').sort(function (a, b) {
  return a.toLowerCase().localeCompare(b.toLowerCase());
}).join('');

If you care to have a case sensitive output e.g. Hello would become eHllo

Community
  • 1
  • 1
anvk
  • 1,183
  • 8
  • 10