Create an ascending order sort function for the Javascript array in it’s prototype property

In this article we will create a special function for the Javascript’s Array object which will sort all the elements in an array in the ascending order. Javascript array does provides an ascending sort method but it will only sort the characters but not the numbers. If you sort the below array with it’s sort method then you will get a strange outcome.

var numbers = [8, 94, 1, 10, 3];
console.log(numbers.sort()); // output [ 1, 10, 3, 8, 94 ]

What the above sort method of the Array object does is just to convert the number into string and then compares them with each other which will result in the above strange outcome. Therefore if we want to really sort an array then we will need to create a new function under the Array object prototype property.

If you search on the Internet you will notice that there is already a sort solution known as bubble sort which We will use in our function to do the true array’s sort. Here is how the bubble sort looks like, go ahead and understand it first before we move further.

var length = this.length;  
var temp = 0;  
for(var i=0; i < length; i++){  
 for(var j=1; j < (length-i); j++){  
   if(this[j-1] > this[j]){    
       temp = this[j-1];  
       this[j-1] = this[j];  
       this[j] = temp;  
   }  
                      
 }  
}  

Next we can simply create a new function under the Javascript Array prototype property to sort the entire array in ascending order and return the result.

Array.prototype.trueSort = function() {
    var length = this.length;  
    var temp = 0;  
    for(var i=0; i < length; i++){  
    	for(var j=1; j < (length-i); j++){  
    		if(this[j-1] > this[j]){    
                temp = this[j-1];  
                this[j-1] = this[j];  
                this[j] = temp;  
             }  
                      
    	}  
     }  
     return this; // return the array object
};

The this keyword in the above program simply refers to the array object it selves.

Next sort the above array again and you will get the correct answer.

var numbers = [8, 94, 1, 10, 3];
console.log(numbers.trueSort()); // output [ 1, 3, 8, 10, 94 ]

The prototype property of an object or constructor allows us to attach a method or a property under that object or constructor which is very useful indeed!

Update, a discussion in reddit shows that we can actually sort the numbers with the sort method as well by providing a sort function to the sort method.

var numbers = [8, 94, 1, 10, 3];
console.log(numbers.sort((a, b) => a - b)); // output [1, 3, 8, 10, 94]

If you do the search on google you will not find the above solution, you do need to dig deep into the document of this method to find out that it actually accepts a comparable function as it’s parameter which will be used in the numerical sort.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of