Thursday, August 22, 2019

javascript sort method does not change order if the return value is not integer

When calling sort method on array with object element, a compare method is passed as parameter to compare each element.

customComparator: (i1, i2)=>{
let ret = i1[fieldToCompare]<i2[fieldToCompare]; //return ret; //this does not work!!! return ret? -1: 1; }

myArray.sort(customCompaartor);

Many languages allow the compare method to return boolean value or integer value. However, for javascript and typescript, the compare method must return an integer, so 

If the result is negative i1 is sorted before i2.
If the result is positive i2 is sorted before i1.
If the result is 0 no changes are done with the sort order of the two values

If a boolean value is returned, no matter it is true or false, the order of the array will not be changed.

No comments:

Post a Comment