2

I would like to sort an array in JavaScript as asc. After I used sort method, the result is like below.

[ '123, '12', '1A1', '1A', '1a', 'A1', 'A2', 'AB', 'A', 'Ab', 'a1', 'a2', 'aB', 'ab' ]

When I'm using sort Array.Sort() by C#, the result is like below.

{ "12", "123", "1a", "1A", "1A1", "A", "a1", "A1", "a2", "A2", "ab", "aB", "Ab", "AB" }

Actually the C# sort way is what I want, so how to implement it in JavaScript? Has anyone completed this task before? A comparator function is really appreciate.

9
  • why this is down vote and the answers are up votes. Don't get it, write a new function is not the answer of the question. Commented Sep 13, 2014 at 10:05
  • @T.J.Crowder The order he specifies is actually what C# Array.Sort gives. Commented Sep 13, 2014 at 10:13
  • Have you notice that A is a single character? I guess so C# has special operation inside the sort method for it. Suppose C# sort is an expected result, now I want to use JavaScript to match it. Commented Sep 13, 2014 at 10:14
  • Here's the ideone.com for it... ideone.com/ZLKC8M It looks as though C# is ordering the string multiple times, going through the characters one by one, e.g. OrderBy([0]).ThenBy([1]).ThenBy([2]) and so on Commented Sep 13, 2014 at 10:16
  • 1
    @Damon I removed my question about writing own JavaScript function based on decompiled C# code. C# uses InternalCompareString Windows API function and there are too lot of conditions... It will be easier to write your own C# delegate function for sorting rather than investigate implementation of InternalCompareString Windows API. Commented Sep 13, 2014 at 11:07

1 Answer 1

1

Array.prototype.sort uses string comparison by default. It seems you want to compare case insensitive - you could pass in a comparator function that uses toLowerCase (but beware of the difference with .toLocaleLowerCase!):

a.sort(function(a, b) {
  a = a.toLowerCase(); b = b.toLowerCase();
  return a > b ? 1 : a < b ? -1 : 0;
});
Sign up to request clarification or add additional context in comments.

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.