How does sort function work in JavaScript, along with compare function

Viewed 82081

As already asked: how does sort function work in JavaScript, along with the compare function? If I have an array, and I do array.sort(compare) now it was written in the book that if the compare function returns a-b (two indices of the array) then it works based on the fact that whether the result is greater than 0, less than 0 or equal to 0. But, how exactly does it work? I could not work it out.

7 Answers

We can simplify for sorting in normal order and reverse order

first parameter is a.

second parameter is b.

function compare(a, b) {
  //  make some operations to calculate these variables as true or false
  //     weNeedToMoveFirstParameterInPositiveDirection
  //     weDoNotNeedToMove
  //     weNeedToMoveFirstParameterInNegativeDirection

  // just think about numerical axis <------(-1)---(0)---(1)------>
  if (weNeedToMoveFirstParameterInPositiveDirection) return 1;  
  if (weDoNotNeedToMove) return 0; 
  if (weNeedToMoveFirstParameterInNegativeDirection) return -1;  
}

You can use Uint32Array at the moment to create the array.

[https://i.stack.imgur.com/qBgvm.png]

but, it has some difficulties. For example, you can't add a new value to the array. Simply, you can't modify the array length.

Related