- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Implementing Priority Sort in JavaScript
We are required to write a JavaScript function that takes in two arrays of numbers, second being smaller in size than the first.
Our function should be a sorted version of the first array (say in increasing order) but put all the elements that are common in both arrays to the front.
For example − If the two arrays are −
const arr1 = [5, 4, 3, 2, 1]; const arr2 = [2, 3];
Then the output should be −
const output = [2, 3, 1, 4, 5];
Example
Following is the code −
const arr1 = [5, 4, 3, 2, 1]; const arr2 = [2, 3]; // helper function const sorter = (a, b, arr) => { if(arr.includes(a)){ return -1; }; if(arr.includes(b)){ return 1; }; return a - b; }; const prioritySort = (arr1, arr2) => { arr1.sort((a, b) => sorter(a, b, arr2)); }; prioritySort(arr1, arr2); console.log(arr1);
Output
Following is the output in the console −
[ 2, 3, 1, 4, 5 ]
Advertisements