Wrong sorted array.Javascript -


i have following javascript array:

a=[0, "b", 2, 3, 4, 5, 1, 9, 8, "a", "a", 11010] 

now want sort , this

a.sort() 

but following:

[0, 1, 11010, 2, 3, 4, 5, 8, 9, "a", "a", "b"] 

which think wrong because 11010 greater 2 , should after 2. if following:

a.sort(function(a,b){return a-b;}); 

i following:

[0, "b", 11010, 2, 3, 4, 1, 8, 9, "a", "a", 5] 

can explain me why happening?thank you

your array has both numbers , strings. need supply compare function.

a = [0, "b", 2, 3, 4, 5, 1, 9, 8, "a", "a", 11010] a.sort(function(c1, c2) {     if(typeof c1 === "number" && typeof c2 == "number") {         return c1 - c2;     } else {             return (c1 + "").localecompare(c2);     }  ); 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -