Keep It Simple -1: Five Simple Facts of Sort() in VanillaJS

It is always a good idea to get a strong knowledge on basics. We have many ways to sort elements in most of the JavaScript frameworks in angularJS, react JS etc., here lets see how it is done in Plain/VanillaJS.

In JavaScript, sort() always tries to put elements in ascending or alphabetical order if none specified. Here are 5 basic and simple facts about sort() in plain JavaScript-

  1. It sorts the elements with same special characters as expected
    Ex: [‘$5’, ‘$1’, ‘$2’] gives $1, $2, $5 
  2. When same element with different characters are in array then it sorts according to the special char but not based on the digits.
    Ex: [ ‘$3’, ‘*4′,’@1’, ‘&2’] gives $3, &2, *4, @1
  3. It doesn’t sort elements with different number of digits.
    Ex: [1,2,10,3] gives 1,10,2,3
  4. When an empty string is involved with numbers and alphabets, it always puts the empty string at first, then numbers will be sorted in ascending order and then strings will sorted alphabetically.
    Ex: [‘bananas’, ‘apple’, ”,1, 5] gives  ,1,5,apple,banana
  5. If an array has negative numbers involved with positive numbers, it just considers negative numbers together and tries to sort them ascending without considering ‘-‘ and then sorts positive numbers.
    Ex: [1, -15, -1, -3, 2, -2] gives  -1,-15,-2,-3,1,2

Leave a comment