-2

For some reason, sort doesnt sort correctly. Why is that?

console.log(
  [0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0].sort((a,b)=>a<b)
)

But the inverse works....

console.log(
  [0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0].sort((a,b)=>a>b)
)
  • 2
    The comparator function is wrong. [Check the documentation.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Pointy Oct 04 '18 at 12:44
  • https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly – Stefan Blamberg Oct 04 '18 at 12:45
  • That's not how `sort` works, see the linked question's answers. You don't return a boolean, you return a *number*: negative, 0, or positive. More on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort So (if you want an ascending sort): `.sort((a,b) => a -b)` – T.J. Crowder Oct 04 '18 at 12:45

2 Answers2

1

Array.prototype.sort()

To compare numbers instead of strings, the compare function can simply subtract b from a.

The following function will sort the array ascending (if it doesn't contain Infinity and NaN):

console.log(
 [0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0].sort((a,b)=>a - b)
)
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

The function should return either a-b for ascending or b-a for descending

console.log([0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0,5].sort((a,b) => a - b)) 

console.log([0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0,5].sort((a,b) => b - a)) 
  
 
Hary
  • 5,690
  • 7
  • 42
  • 79