1
Vote

OrderByDescending is giving wrong result

description

I am trying to sort the following number
var array = [{ DEFAULT_VALUE: "1" }, { DEFAULT_VALUE: "2" }, { DEFAULT_VALUE: "3" }, { DEFAULT_VALUE: "4" }, { DEFAULT_VALUE: "5" }, { DEFAULT_VALUE: "6" },
{ DEFAULT_VALUE: "7" }, { DEFAULT_VALUE: "8" }, { DEFAULT_VALUE: "9" }, { DEFAULT_VALUE: "10" }];
var s = Enumerable.From(array).OrderByDescending("$.DEFAULT_VALUE").Select("$.DEFAULT_VALUE").ToArray();
console.log(s.toString());
and the result that I am getting is

9,8,7,6,5,4,3,2,10,1

number 10 should appear at first instead of second last. Can anybody tell me whats the actual problem here?

comments

nickkell wrote Feb 28, 2014 at 3:52 PM

I think because the string "9" > string "10", whereas the number 10 > number 9

NathanFriend wrote May 6, 2014 at 9:52 PM

You can produce the sort order you're expecting by first converting each item to a number before sorting the list:
var s = Enumerable.From(array)
        .Select(function (item) { return parseInt(item.DEFAULT_VALUE, 10); })
        .OrderByDescending("$")
        .ToArray();

console.log(s.toString());  // output: "10,9,8,7,6,5,4,3,2,1"