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?

4
  • 10
    "H" < "e" === true Commented Jul 14, 2016 at 18:51
  • 2
    test[1].toLowerCase().split('').sort().join(''); should work. You are sorting then transforming. Commented Jul 14, 2016 at 18:51
  • convert to lower case first and then compare elements Commented Jul 14, 2016 at 18:52
  • using toLowerCase() before the sort did the trick. Thank you for the great replies! Sorry I didn't find the previous thread on the subject. Commented Jul 14, 2016 at 21:51

3 Answers 3

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.

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

Comments

4

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

console.log('Hello'.toLowerCase().split('').sort().join('')); // ehllo

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.