问题
Because I'm using Nativescript I'm using the same Typescript code for Android and iOS.
I have a very large data set of about 1000-2000 (could be bigger) objects with very large data values in an array.
const unsorted = [
...,
{
name: "name1",
value: 10000000
},{
name: "name120",
value: 200000000
},{
name: "name42",
value: 3
},{
name: "name1203",
value: 1000000000000
},
...
];
const sorted = unsorted.sort((a,b) => (b.value-a.value));
On Android, sorted
is always correctly sorted, but iOS is not. The iOS arrays return "half sorted"- the first ten or twenty are sorted correctly but then it randomly has incorrectly sorted values similar to my example below:
[...1003, 26, 1002, 1001, ..., 20, 19, 14, 18, 17, 16, 15, 13, 12, 11, 10]
I found I could get the data to be the same on Android and iOS if I did something messy like:
const secondSort = sorted.sort((a,b) => (b.value-a.value));
const thirdSort = secondSort.sort((a,b) => (b.value-a.value));
const fourthSort = thirdSort.sort((a,b) => (b.value-a.value));
So it may appear that the first sort isn't actually sorting my large data set completely.
Has anyone else seen this behavior? Or is there maybe a brute force way to do this to ensure I don't need to string together several sorting functions?
回答1:
Please take a look at this:
https://stackoverflow.com/a/15507922
It seems WebKit (which NativeScript uses, same as Safari) does not play well with this kind of sort, so you might get a better result by doing:
myArray.sort(function(a,b){
return (b.date > a.date) ? 1 : (b.date < a.date) ? -1 : 0;
});
We already encountered something like it. In our case it was the Date object that had the wrong timezone after you altered it, and we had to use moment.js to solve it... ¯\_(ツ)_/¯
来源:https://stackoverflow.com/questions/54334790/array-sort-not-working-correctly-on-nativescript-ios-for-very-large-arrays-with