7

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 where the error is hidden, but I am not 100% sure.

The output I should get after the sort function is called is 1,2,3. I get 1,3,2 which means that it is unchanged

This is the entire js code (with some comments):

var arr = [];
//object definition and creation
var main = document.getElementById("main");
var task = {
    name: "",
    priority: 0
};

//first
var one = Object.create(task);
one.priority = 1;
//secondd
var two = Object.create(task)
two.priority = 3;
//last
var three = Object.create(task);
three.priority = 2;

//append
arr.push(one);
arr.push(two);
arr.push(three);

//sort function
function sortT() {
    arr.sort(compareFN);
}

//comperator function
function compareFN() {
    return task.priority < task.priority;
}

function print() {
    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i].priority);   
    }
}

//execution of the program
print();
sortT();
print();

EDIT: The solution is the following - As stated, the comparator function really was the problem, the correct way to write it is the following:

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

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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

Comments

1

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.