Javascript sort array by key descending Google Chrome

我的梦境 提交于 2021-01-05 13:16:44

问题


I have an array and need to sort it in descending order by the key. All working good in Firefox but in Chrome it's showing in the original order

[["0", 0], ["1", 0.9], ["2", 597.5344192965547], ["3", 991.0326954186761], ["4", 1257.2580315846578], ["5", 1293.5250901880618], ["6", 2197.1091224116512], ["7", 2225.0422585266947], ["8", 3964.1307816747044], ["9", 6914.072436146399]]

This is the code I am using

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

So in Firefox it returns the correct result

[["9", 6914.072436146399], ["8", 3964.1307816747044], ["7", 2225.0422585266947], ["6", 2197.1091224116512], ["5", 1293.5250901880618], ["4", 1257.2580315846578], ["3", 991.0326954186761], ["2", 597.5344192965547], ["1", 0.9], ["0", 0]]

But in google Chrome it just displays the same


回答1:


You have an array of arrays. Assuming sortable refers to the outer array, your sorting function ends up using - on array instances. For instance, at some point when you call sort, your sorting function is called with the arrays ["0", 0] and ["1", 0.9]. So you effectively do this in that function:

return ["0", 0] - ["1", 0.9];

Using - on those two operands will result in the JavaScript engine trying to turn those operands into numbers, almost certainly resulting in NaN. NaN - NaN is NaN, which isn't one of the things the sorting comparator callback is supposed to return.

I suspect you want to sort by the first entry in the subordinate arrays, like this:

sortable.sort(function(a,b){return b[0]-a[0]})

(Note the [0] on each.) That will get the strings that are the first entries in each subordinate array and pass them to -, which will implicitly coerce them to numbers. You could also make that explicit and force a specific radix if desired:

sortable.sort(function(a,b){return parseInt(b[0], 10) - parseInt(a[0], 10)})


来源:https://stackoverflow.com/questions/22759290/javascript-sort-array-by-key-descending-google-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!