How to sort array of numbers in JavaScript Easily

Hello programmers, I am again here to show you how to sort an array of numbers in JavaScript easily. I know that using the sort method you can easily sort an array of strings. But what will happen if the array is containing numbers? for those array containing numbers, you can not sort the numbers just by using sort() method.
Because of sort() method takes its input as strings, not as numeric values.
So in this post, we gonna learn how to sort array of numbers in JavaScript or you can say soring numeric array in JavaScript.

Sort array of numbers in JavaScript Easily

Before going to the direct code snippet I would like to let you know why we can’t use sort() method directly to sort array containing numbers or integers value.

How to find the Keycode in JavaScript ( Core JavaScript no jQuery )

Let’s just assume that we have a string like this:

var tutorials = ["Java", "PHP", "JavaScript", "Python"];

It will sort the elements just like the dictionary sorts its words.

But in case of integers value?

Free cool 3d image hover effect source code download

Assume that we have a string like this:

var numbers = [41, 154, 7, 59, 125, 10];

Now, if we use numbers.sort() just imagine what will happen?

sort() method deals with string so if the numbers are taken as a string also it will give you the incorrect result.
“41” will be greater than “154” because of 4 > 1

Also read,

How to count capital letters and small letters in JavaScript

To overcome this error we can use the compare function.

var numbers = [41, 154, 7, 59, 125, 10];
numbers.sort(function(a, b){return b - a});

This is known as compare function. It returns positive negative or zero. If a==b then it will return 0. If a<b it will return negative. If a>b it will return positive.

That means it will first compare 41 with 154. Thus 41-154 is a negative value, So the function will consider 40 as lower than 154.

How To Change Background Color Every Seconds in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *