Create a Priority Queue Class Not passing test. Why?

Tell us what’s happening:
Why does this not part the test. I get the following error

// running tests

The priority queue should return items with a higher priority before items with a lower priority and return items in first-in-first-out order otherwise.

// tests completed

Your code so far


function PriorityQueue () {
    this.collection = [];
    this.printCollection = function() {
      console.log(this.collection);
    };
    // Only change code below this line
    this.enqueue = function(speciesAndPriority) {
      this.collection.push(speciesAndPriority);
      console.log(this.collection);

     let sorted =  this.collection.sort(sortfunction)

      function sortfunction(a,b) {
        if(a[1] === b[1]) {
          return 0;
        }else{
         return (a[1] - b[1]) ? -1 : 1;
        }
      }
       this.collection = sorted;
       return this.collection

    };
    this.dequeue = function() {
      let itemRemoved = this.collection.shift();
      return itemRemoved;
    };
    this.size = function() {
      return this.collection.length;
    };
    this.isEmpty = function() {
        if(this.collection.length === 0) {
            return true;
        }
    };
    // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-priority-queue-class

This line of code in the sortfunction

return (a[1] - b[1]) ? -1 : 1;

always returns true for a[1] - b[1] !== 0, which probably wasn’t your intention, because the ternary operator ? evaluates the first operand a[1] - b[1] as a boolean value, so the numeric result is implicitly converted to a boolean value. 0 is false, non 0’s are true.

Also, you are returning the entire array in the dequeue function, but the question asked to return only the item, not its priority.

In your code:

this.dequeue = function() {
      let itemRemoved = this.collection.shift();
      return itemRemoved;
};

itemRemoved is an array, because shift returns the first element of an array. And since this.collections is an array of arrays, its first element is an array (with the item in index 0 and priority in index 1)