I am using anArrayOfObjects.sort((a, b) => a.value - b.value)
, where some objects don't have a value
property.
That leads to different results in Firefox and Chrome, where Chrome seems to sort the object(s) with no value
property/undefined value to the end, Firefox doesn't.
Is the spec not prescribing the result that Chrome gives, meaning the Firefox result is wrong? Or is that part of the sort
result up to a particular implementation?
const data2 = [
{ 'name' : 'a', 'value' : 5 },
{ 'name' : 'b', 'value' : 2 },
{ 'name' : 'c' },
{ 'name' : 'd', 'value' : 1 }
];
console.log('before sorting: ', data2);
data2.sort((a, b) => a.value - b.value);
console.log('after sorting: ', data2);
Neither are "wrong".
undefined - undefined
, undefined - 1
and 1 - undefined
all return NaN
, and NaN
compared to something is always false
.
The difference between the 2 browsers is probably due to sorting implementation.
The used sorting algorithm can give different results, depending on the order of values beforehand, and how the implementation deals with NaN
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With