Leon Schreiber
Leon Schreiber

Reputation: 91

JavaScript sort with seemingly inconsistent results

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.

Upvotes: 0

Views: 275

Answers (1)

Drdilyor
Drdilyor

Reputation: 1377

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
}))

Upvotes: 1

Related Questions