0

I'm trying to sort an array of numbers, but one value should be prioritized above all others, meaning it should always come out at the end of the sorted array.

I was trying playing around, trying to find a suiting sort function and stumbled upon results I don't understand.

My results

You can see my sort function, and it's exactly the same in both cases. From my understanding, it should return 1 if a is bigger than b. Shouldn't having a fixed return value for a = 2 make 2 the "biggest" number? It seems to work with the first array, but not with the second one, so the results depend on the input array. I tried this with a lot of different inputs and I can't find a pattern for when it works and when it doesn't.

1
  • 1
    That sort comparator function is inherently invalid. You must return a consistent comparison result for any pair of elements, and that must take into account that "a" and "b" may be the same two elements you've compared before but in reverse order. Commented Apr 19, 2021 at 15:17

1 Answer 1

1

You should check if b is 2 as well, this works:

console.log([5, 4, 3, 2, 1].sort((a, b) => {
  if (a === 2) return 1
  if (b === 2) return -1
  return a - b
}))

Sign up to request clarification or add additional context in comments.

Comments

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.