1

I'm trying to sort array of strings ['d', 'CC', 'BB', 'b', 'a', 'Am','AMG'] in such order ["AMG", "Am", "a", "BB", "b", "CC", "d"]

Using

arr.sort(function (a, b) {
  return a.toLowerCase().localeCompare(b.toLowerCase());
});

I get ["a", "Am", "AMG", "b", "BB", "CC", "d"]

5
  • because, a < am < amg < b < bb < cc < d - look in a dictionary ... the entry for a comes before the entry for am Commented Jul 14, 2018 at 9:35
  • your required order makes no sense Commented Jul 14, 2018 at 9:40
  • what is the rule behind? Commented Jul 14, 2018 at 9:40
  • First capital, than lower case Commented Jul 14, 2018 at 9:41
  • You're going to need something fancy then .. because localeCompare makes a < A and you want a > A Commented Jul 14, 2018 at 9:46

1 Answer 1

2

You could chain some sort criteria, after swapping the case of the letters, then

  • sort by first lower case characters ascending,
  • sort by length descending
  • sort by string ascending

function swap(s) {
    return Array.from(s, c => c.toUpperCase() === c ? c.toLowerCase() : c.toUpperCase()).join('');
}

var array = ['d', 'CC', 'BB', 'b', 'bb', 'a', 'Am', 'AMG'];

array.sort((a, b) => {
    var aa = swap(a),
        bb = swap(b);

   return a[0].toLowerCase().localeCompare(b[0].toLowerCase())
       || bb.length - aa.length
       || aa.localeCompare(bb);
});

console.log(array); // ["AMG", "Am", "a", "BB", "b", "CC", "d"]

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

1 Comment

if have ['bb', 'BB'] sort fails ["AMG", "Am", "a", "bb", "BB", "CC", "d"]

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.