3

I have an array which looks like

var arr = [{'Id':'1','Value':'Desk'},
     {'Id':'2','Value':'skool'},
     {'Id':'3','Value':'OT'},
     {'Id':'4','Value':'sector'},
     {'Id':'5','Value':'Security'},
     {'Id':'6','Value':'Zebra'},

I would like to sort this array to get a result

[
  { Id: '1', Value: 'Desk' },
  { Id: '3', Value: 'OT' },
  { Id: '4', Value: 'sector' },
  { Id: '2', Value: 'skool' },
  { Id: '5', Value: 'Security' },
  { Id: '6', Value: 'Zebra' }
]

I have tried doing

arr.sort((a,b) => (a.Value.toLocaleLowerCase() > b.Value.toLocaleLowerCase()) ? 1 : ((b.Value.toLocaleLowerCase() > a.Value.toLocaleLowerCase()) ? -1 : 0)); 

which gave me a result

[
  { Id: '1', Value: 'Desk' },
  { Id: '3', Value: 'OT' },
  { Id: '4', Value: 'sector' },
  { Id: '5', Value: 'Security' },
  { Id: '2', Value: 'skool' },
  { Id: '6', Value: 'Zebra' }
]

Difference is the order of skool and Security. I want all my lower case letters to come up first and then upper case letters. What can I try to achieve this?

2
  • What is toLocaleLowerCase supposed to do? Commented Jun 11, 2020 at 21:02
  • it's looks like stackoverflow.com/questions/62316839/… (well, in the answer you has parentId, here you has, if Value[0] is lowercase, parentId=Value[0].toUpperCase() else null ) Commented Jun 12, 2020 at 7:20

3 Answers 3

1

Do you want to sort by alphabetical order or case wise? If you are sorting alphabetically you can't get Security after skool because alphabetically, e comes before k.

If you want to that -

  • If first letter of two words is same, then sort the lowercase first irrespective of consideration of further alphabetical order.

In that case you could use following -

var arr = [{
    Id: '1',
    Value: 'Desk'
  },
  {
    Id: '3',
    Value: 'OT'
  },
  {
    Id: '4',
    Value: 'sector'
  },
  {
    Id: '2',
    Value: 'skool'
  },
  {
    Id: '5',
    Value: 'Security'
  },
  {
    Id: '6',
    Value: 'Zebra'
  }
];


arr.sort(function(a, b) {
  //if exactly same strings, return 0
  if (a.Value === b.Value)
    return 0;
  //if first case of a and b are unequal return based on case
  if (a.Value.toLocaleLowerCase()[0] === b.Value.toLocaleLowerCase()[0] && a.Value[0] !== b.Value[0])
    return a.Value[0] < b.Value[0] ? 1 : -1;
  //Now return 0 if both are equal in lower case else return 1 or -1 depending on comparison below
  if (a.Value.toLocaleLowerCase() === b.Value.toLocaleLowerCase())
    return 0;
  return a.Value.toLocaleLowerCase() > b.Value.toLocaleLowerCase() ? 1 : -1;

});


//Apparently below code is not the exactly right way to do it, so use the above method
//arr.sort((a, b) => (a.Value.toLocaleLowerCase()[0] === b.Value.toLocaleLowerCase()[0]) ? (a.Value[0] > b.Value.[0]?1:-1) : (a.Value.toLocaleLowerCase() > b.Value.toLocaleLowerCase()?1:-1));

console.log(arr);

In the above snippet, if the first letters of any two words are same, they will be sorted based on the case of their first letter. In all other cases, it will be sorted alphabetically.

EDIT : As per the comment suggestion, for a sort function in TS, it should return -

  • 1 : when a > b,
  • 0 : when a === b and
  • -1 :when a < b.

So, a more correct(as well as readable) version has been mentioned in the answer.

Hope this helps !

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

6 Comments

Hi, I want the result to be like this only, but when I try to execute the same in my typescript code, I get an error msg Type 'boolean' is not assignable to type 'number'
@cvg I haven't used typescript. Are you sure that you are getting error in sort function? coz I think the function is JS syntactically correct.
@Abhishek the function is syntactically correct but it returns a boolean, not a number
@cvg I have edited the answer and now the function should work correctly.
You never return -1 (or a negative vale). So now it doesn't return a boolean type but it's still only two values, not three. This can potentially lead to incorrect sorting results.
|
0

Try this:

var arr = [{'Id':'1','Value':'Desk'},{'Id':'2','Value':'skool'},{'Id':'3','Value':'OT'},{'Id':'4','Value':'sector'},{'Id':'5','Value':'Security'},{'Id':'6','Value':'Zebra'}];
var sort = (a, b) => a > b ? 1 : (a < b ? -1 : 0);
var sorted = arr.sort((a,b) => 
  sort(a.Value[0].toLowerCase(), b.Value[0].toLowerCase()) || 
  -sort(a.Value[0], b.Value[0]) ||
  sort(a.Value, b.Value));
console.log(sorted);

1 Comment

That doesn't answer OP's question. The requirement was to sort skool after sector,that is sort alphabetically when first character are of same case, while in your case it's not sorted accordingly. Please edit the post to match the requirement
0

Just to have in your bag of tricks, if you want to alphabetize all lower case letters first, then follow that up with all capitalized letters, you can use this:

arr.sort(function (a, b) {
    if (a.Value[0] === a.Value[0].toLowerCase() && b.Value[0] === b.Value[0].toLowerCase() ||
        a.Value[0] === a.Value[0].toUpperCase() && b.Value[0] === b.Value[0].toUpperCase()) {
        return a.Value.localeCompare(b.Value);
    }
    if (a.Value[0] === a.Value[0].toLowerCase()) {
        return -1;
    }
    return 1;
});

Here is the output:

[ { Id: '4', Value: 'sector' },
  { Id: '2', Value: 'skool' },
  { Id: '1', Value: 'Desk' },
  { Id: '3', Value: 'OT' },
  { Id: '5', Value: 'Security' },
  { Id: '6', Value: 'Zebra' } ]

3 Comments

Please take a look on the expected output.. your output can be archived with a simple arr.sort(function (a, b) {a>b?1:-1});
The expected output order is: Desk, OT, sector, skool, Security, Zebra. please take a look at the question. there is demo of expected output shown explicitly
I understand that. His initial sort was from my comment in a duplicate thread he made. We've actually talked back and forth in the thread before, so I wanted to give him this potion since the requirements were a little unclear.

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.