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?

5
  • I suppose it does not sort because your function has no explicit return value in the case a.index <= b.index. Commented Sep 7, 2016 at 10:43
  • @MartinNyolt How should I change the code to reflect that? Commented Sep 7, 2016 at 10:44
  • See this answer. Commented Sep 7, 2016 at 10:45
  • panoramas.sort((a, b) => a.index - b.index) Commented Sep 7, 2016 at 10:50
  • 1
    Do you mean IE changes the values of the object properties? I mean the example code definitely doesn't sort arrays in any browser. Notice also, that IE doesn't support ES6 arrow functions. Commented Sep 7, 2016 at 10:54

1 Answer 1

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; 
});
Sign up to request clarification or add additional context in comments.

2 Comments

return a.index - b.index is much more concise.
thnx @MartinNyolt. had the verbose solution because I think it will be easier to understand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.