- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add elements to a PriorityQueue using Javascript
Enqueuing elements to a PriorityQueue means adding them in the array in order of the priority of the element. We'll consider higher numbers to be higher priorities. We'll loop through the container till we find a lower priority and then add the element there. If not, then we'll push it at the end of the container.
Note that we're creating the element object with the data and priority. Hence we can implement the enqueue function as follows −
Example
enqueue(data, priority) { // Check if Queue is full if (this.isFull()) { console.log("Queue Overflow!"); return; } let currElem = new this.Element(data, priority); let addedFlag = false; // Since we want to add elements to end, we'll just push them. for(let i = 0; i < this.container.length; i ++) { if(currElem.priority < this.container[i].priority) { this.container.splice(i, 0, currElem); addedFlag = true; break; } } if (!addedFlag) { this.container.push(currElem); } }
You can check if this function is working fine using −
Example
let q = new PriorityQueue(4); q.enqueue("Hello", 3); q.enqueue("World", 2); q.enqueue("Foo", 8); q.display();
Output
This will give the output −
[ { data: 'World', priority: 2 }, { data: 'Hello', priority: 3 }, { data: 'Foo', priority: 8 } ]
As you can see the elements are in a sorted order. The enqueue function works like insertion sort's insertions.
- Related Articles
- Remove elements from a PriorityQueue using Javascript
- Peeking elements from a PriorityQueue using JavaScript
- Clearing the elements of the PriorityQueue using Javascript
- Add elements to a Queue using Javascript
- Add elements to a Set using Javascript
- Add elements to a linked list using Javascript
- Add elements to a hash table using Javascript
- How to add HTML elements dynamically using JavaScript?
- Add elements to a Dictionary in Javascript
- The PriorityQueue Class in Javascript
- How to add rows to a table using JavaScript DOM?
- Inserting Elements to a doubly linked list using Javascript
- How to add a number of months to a date using JavaScript?
- Remove elements from a queue using Javascript
- Remove elements from a Set using Javascript

Advertisements