JavaScript sort comparator function

后端 未结 4 840
梦毁少年i
梦毁少年i 2021-01-21 08:05

Basically I want to build a function which sorts objects in an array by one of the object\'s properties/member variables. I am preeeety sure that the comparator function is wher

相关标签:
4条回答
  • 2021-01-21 08:37

    You need to change the signature of you compare function to include the two tasks.

    For ascending order (normally what you want) you need to do b < a, a < b will do descending order

    //comperator function
    function compareFN(a, b) {
        return b.priority < a.priority;
    }
    
    0 讨论(0)
  • 2021-01-21 08:39

    The comparator function returns a negative value, zero or a positive value. Those three comprise what is called here the three-way comparison. So: ''' function cmp((a, b) => { // ascending return a - b } ''' For descending return b - a

    0 讨论(0)
  • 2021-01-21 08:44

    There are multiple problems with your comparator:

    1. It refers to the global task object instead of the objects being compared.
    2. It compares the object to itself.
    3. It is supposed to perform a three-way comparison.

    Try:

    var compareFN = function(a, b) {
        return a.priority - b.priority;
    }
    
    0 讨论(0)
  • 2021-01-21 08:56

    The compare function needs two arguments: the first and the second element it should compare. So your compareFN should look like this:

    function compareFN(taskA, taskB) {
       return taskA.priority - taskB.priority;
    }
    

    Edit: As NPE said, it is supposed to perform a three-way comparison, so a simple a < b is not so a great idea here.

    0 讨论(0)
提交回复
热议问题