Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Javascript sort() function is not giving the expected output? [duplicate]

Possible Duplicate:
sort not working with integers?
How to sort number in javascript sort method
Array.sort() doesn't sort numbers correctly

Code:

var x = [40,100,1,5,25,10];
x.sort();

output:

1,10,100,25,40,5

My expected output:

1,5,10,25,40,100
like image 371
ehp Avatar asked Aug 11 '12 12:08

ehp


People also ask

Why JavaScript sort is not working?

This is because sort() needs a callback comparator, and when sort() is used without one, String() acts as the default callback. This is our callback function that will help sort the numbers in the correct and ascending order.

How will you sort an array with many duplicated values?

A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.

What does JavaScript sort return?

sort() returns the reference to the same array The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

Does sort return?

sort() Return Value The sort() method doesn't return any value.


1 Answers

The JavaScript Array .sort() function by default converts the array elements to strings before making comparisons.

You can override that:

x.sort(function(e1, e2) { return e1 - e2; });

(The function passed should return a number that's negative, zero, or positive, according to whether the first element is less than, equal to, or greater than the second.)

I've never seen a rationale for this odd aspect of the language.

like image 66
Pointy Avatar answered Sep 23 '22 08:09

Pointy