0

I have a very simple sorting function that sorts objects by index:

panoramas.sort((a, b) => {
  if (a.index > b.index) return 1
})

Input:

[
  { index: 0 },
  { index: 2 },
  { index: 1 }
]

Output:

[
  { index: 1 },
  { index: 2 },
  { index: 3 }
]

The function works in Chrome and Firefox, but not in IE (the array isn't being sorted at all.)

Is there something wrong with my function?

alex
  • 7,111
  • 15
  • 50
  • 77

1 Answers1

4

The sorting function should return -1, 0 or 1 for the ordering.

// Your function tests for 'a.index > b.index'
// but it's missing the other cases, returning false (or 0)

panoramas.sort((a, b) => {
  if (a.index > b.index) return 1;
  if (a.index < b.index) return -1;
  return 0;
})

from Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

  • > 0 when a is considered larger than b and should be sorted after it
  • == 0 when a is considered equal to b and it doesn't matter which comes first
  • < 0 when a is considered smaller than b and should be sorted before it

for numbers, you can use a more concise approach:

panoramas.sort((a, b) => {
   return a.index - b.index; 
   // but make sure only numbers are passed (to avoid NaN)
})

for IE11, that as noted by @teemu doesn't support arrow functions, you'll have to use a function expression:


panoramas.sort(function(a, b) {
  return a.index - b.index; 
});
Community
  • 1
  • 1
bfmags
  • 2,885
  • 2
  • 17
  • 28