Saturday, 15 September 2018

JavaScript: sort: Sort elements of array

JavaScript provides sort function to sort elements of array. By default, sort function converts everything to string and uses lexicographical order.

Syntax
sort([function])

var arr = [1, 2, 15, 25, 3];
arr.sort();

As I said, sort function sorts in lexicographical order by default, so above statement sorts elements in following order.
1,15,2,25,3

But this is not what we want. We want to sort elements in ascending order. You can do this by passing custom function like below as an argument to sort() function. Our custom function should take two arguments a, b and return
         1 if a > b,
         -1 if a < b
         0 if a == b

function compare(a, b){
         if(a > b) return 1;
         else if(a < b) return -1;
         else return 0;
}

Sort array using following statement.
arr.sort(compare);

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        function compare(a, b) {
            if (a > b) return 1;
            else if (a < b) return -1;
            else return 0;
        }

        var arr = [1, 2, 15, 25, 3];

        document.write("arr = " + arr + "<br />");

        arr.sort(compare);

        document.write("arr = " + arr + "<br />");
    </script>
</body>

</html>

Open above page in browser, you can able to see following data.

arr = 1,2,15,25,3
arr = 1,2,3,15,25

To sort elements in descending order, use following compare function.

function compare(a, b){
         if(a > b) return -1;
         else if(a < b) return 1;
         else return 0;

}


Previous                                                 Next                                                 Home

No comments:

Post a Comment