Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different result with Array.sort(comparisonFunction) in Chrome and Firefox

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);
like image 332
Martin Honnen Avatar asked Sep 11 '25 14:09

Martin Honnen


1 Answers

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.

like image 107
Cerbrus Avatar answered Sep 14 '25 02:09

Cerbrus