Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of decimal & whole numbers [duplicate]

I can't seem to figure this one out.

var arr = [2.62, 111.05, 1.05]
arr.sort(); 

This returns [1.05, 111.05, 2.62], but I'm expecting [1.05, 2.62, 111.05].

How can this be achieved? I've read a bit about writing a custom sort to split the "decimal" but haven't managed to have any success.

like image 969
zoosrc Avatar asked Feb 10 '15 21:02

zoosrc


People also ask

How do you sort a number in an array?

sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.

How do I sort an array?

Just like numeric arrays, you can also sort string array using the sort function. When you pass the string array, the array is sorted in ascending alphabetical order. To sort the array in descending alphabetical order, you should provide the Collections interface method reverseOrder () as the second argument.

How do you sort an array of numbers in descending order?

We can use . sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or . sort((a,b)=>b-a) for descending order.


1 Answers

By default sorting is alphabetically. You need to pass a function to the sort method

arr.sort(function(a, b){return a-b;});
like image 65
styvane Avatar answered Oct 03 '22 23:10

styvane