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
Post a Comment