Difference between sorting string array and numerical array in jQuery

To sort any array, there is a predefined method called "sort" which sorts the array. sort() method sorts the string array in alphabetical order. This method sorts on the basis of the Unicode code points, so it is better to have all uniform names. That is, they must begin with either uppercase or lowercase, but not mixed case. So to sort any string array use the sort method.

Earlier I had posted about jQuery solution to remove item from array, split an array, combine/join arrays, remove duplicate items from array and Find index of element in array, And In this post, find Difference between sorting string array and numerical array in jQuery.

Below jQuery code sort the string array.

$(document).ready(function() {
  var list= [ "jQuery", "Dojo", "JavaScript", "Ajax"];
  $('#alltech').html(list.join(""));
  list = list.sort();
  $('#sorted').html(list.join(""));
})

See result below.

See Complete Code

Now, declare any numerical array and try to use the sort method on this. Just try the below code to check the output.

$(document).ready(function() {
  var list= [ 45, 32, 98, 24, 16, 9, 3];
  $('#allnumber').html(list.join(""));
  list = list.sort();
  $('#sorted').html(list.join(""));
})

See result below.

Surprised!!!!!!!

Well, the numerical values are not sorted correctly with the sort() method because as mentioned earlier that it considers the Unicode code points value of the first numerical digit of all numerical values for sorting purposes. To sort numerical values correctly, we must define a comparison function with sort().

If we define a comparison function, then a pair of values from the array will be repeatedly sent to the function until all elements of the array are processed. In the comparison function, we thus write a statement considering the pair of values passed to it so that the function returns any of the following three values: <0, =0, or >0.

  • When the function returns value <0, the second value (of the pair of array values sent to the function) is larger than the first value and hence must be pushed down the sorting order. 
  • When the function returns value >0, the first value is larger than the second value, so it must be pushed down the sorting order.
  • When the function returns value =0, it means there is no need to change the sort order since the two values are same.
$(document).ready(function() {
  var list= [ 45, 32, 98, 24, 16, 9, 3];
  $('#allnumber').html(list.join(""));
  list = list.sort(function(a,b){
        return a-b;
    });
  $('#sorted').html(list.join(""));
})

See result below.

See Complete Code

Hope you find this post useful.

Feel free to contact me for any help related to jQuery, I will gladly help you.

Credit : jQuery Recipes



Responsive Menu
Add more content here...