Simple javascript function to sort an int array by ASC.

Simple function to sort an array of ints by ASC order, there are built in methods to sort an array, this is just for fun.


function sort(array) {
    var len = array.length;
    var new_ = array;</div>
   for(var x = 0; x < len; x++) {
        for(var i = 0; i < len; i++) {
           if(array[x] < new_[i]) {
                var tmp = new_[i];
                new_[i] = array[x];
                array[x] = tmp;
            }
        }
    }
}

This is the built in function:


var myArray=[8,10,50,5,7,83,24,19,168];

myarray.sort(function(a, b) {
    if(a > b) {
        return 1;
    } else {
       return -1;
    }
});

 

now with a proper way:


myArray.sort(function(a, b) { return a > b ? 1: -1; });

And even better with arrow (ES6):


myArray.sort((a, b) => a > b ? 1 : -1);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s