how to sort and reverse in array numbers using javascript

     In javascript will when we use the sort() method to sort the array, I will not give the exact result for numbers, it will sort the words only.

eg:)
    var ar=[45,9,200];
     Although 9 is numerically smaller than 45 or 200, lexicographically, it is larger, so 9 appears at the very right of the sorted array. Remember, by default array.sort() sorts its elements in lexicographical order.

Answer is
    ar.sort()   => [9,45,200]

 So we can use the following method to solve this problem.


sort() for numbers

    ar_num.sort(function(a, b)

    {

      return a - b;

    });


reverse() for numbers

    ar_num.sort(function(a, b)

    {

      return b - a;

    });

Example Program:- (Editor)


Editor is Loading...

Advertisement





Tag:
sort() method not working in numbers, reverse() not working in number in javascript, allinworld99 to solve number sort() and reverse() method.

0 nhận xét:

Đăng nhận xét