Remove elements from a PriorityQueue using Javascript

Dequeuing elements from a PriorityQueue means removing the element with the highest priority. Since we store elements with the highest priority at the end of the array, we can simply pop it to dequeue it.

Priority Queue Structure World Priority: 2 Hello Priority: 3 Foo Priority: 8 Highest Priority (Dequeued First)

Dequeue Implementation

The dequeue function removes and returns the highest priority element from the queue:

dequeue() {
    // Check if empty
    if (this.isEmpty()) {
        console.log("Queue Underflow!");
        return;
    }
    return this.container.pop();
}

Complete Example

Here's a complete working example demonstrating the dequeue operation:

class PriorityQueue {
    constructor() {
        this.container = [];
    }
    
    isEmpty() {
        return this.container.length === 0;
    }
    
    enqueue(data, priority) {
        const element = { data, priority };
        let added = false;
        
        for (let i = 0; i < this.container.length; i++) {
            if (element.priority < this.container[i].priority) {
                this.container.splice(i, 0, element);
                added = true;
                break;
            }
        }
        
        if (!added) {
            this.container.push(element);
        }
    }
    
    dequeue() {
        if (this.isEmpty()) {
            console.log("Queue Underflow!");
            return;
        }
        return this.container.pop();
    }
    
    display() {
        console.log(this.container);
    }
}

// Test the dequeue function
let q = new PriorityQueue();
q.enqueue("Hello", 3);
q.enqueue("World", 2);
q.enqueue("Foo", 8);

console.log("Dequeued element:", q.dequeue());
console.log("Remaining queue:");
q.display();
Dequeued element: { data: 'Foo', priority: 8 }
Remaining queue:
[ { data: 'World', priority: 2 }, { data: 'Hello', priority: 3 } ]

Key Points

  • The dequeue() method removes the highest priority element
  • It uses pop() since highest priority elements are stored at the end
  • Always check for underflow (empty queue) before dequeuing
  • Returns the removed element or undefined if queue is empty

Conclusion

Dequeuing from a priority queue is efficient with O(1) time complexity since we simply pop from the end. Always verify the queue isn't empty to prevent underflow errors.

Updated on: 2026-03-15T23:18:59+05:30

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements