I am trying to sort the following two dimensional array in a descending order by the first column:
wordsAndCount = [[0,"string"],[4,"string"],[31,"string"],[1,"string"],[3,"string"]];
wordsAndCount.sort();
wordsAndCount.reverse();
For some reason, JavaScript is treating the first column as a string rather than an integer, returning the following output:
[4,"string"],[31,"string"],[3,"string"],[1,"string"],[0,"string"]
When the desired output should be:
[31,"string"],[4,"string"],[3,"string"],[1,"string"],[0,"string"]
What’s causing JS to do that?
JavaScript is treating the whole element as a string, not just the first element.
sort(), without any sort function specified, will calltoString()on each element it looks at. CallingtoString()on elements like yours, in all JavaScript engines I know, will give values like"[0,\"string\"]"You should specifiy your own sorter function to fix this:
There’ll also be no need to use
reverse()then.For more info, see the MDC documentation on
sort().