Interger /Number Array Sorting in Javascript.

Javascript arrays have the sort() method which sorts the items of an array. By default, the sort() method sorts the values as strings in alphabetical and ascending order.

var names = ["John", "Mary", "Amol", "Robert"];

It is an inplace sort for an array and sorted array would be some thing like this

["Amol", "John", "Mary", "Robert"]

However, if numbers are sorted as strings, “25” is bigger than “100”, because “2” is bigger than “1”. Because of this, the sort() method will produce an incorrect result when sorting numbers. You can fix this by providing a “compare function”


Compare function will look some thing like this

function compareFunction(a, b){
	return a-b

When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

So final number array example looks something like this.

var numberArr = [100, 1, 200, 150, 10, 20];
function compareFunction(a, b) {
    return a - b

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s