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 return a sorted version of the first array (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 ?

[2, 3, 1, 4, 5]

How It Works

The priority sort algorithm works by using a custom comparator function that:

  • Prioritizes elements that exist in the priority array (arr2)
  • Maintains ascending order for non-priority elements
  • Uses the native JavaScript sort() method with custom logic

Implementation

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);
[ 2, 3, 1, 4, 5 ]

Alternative Approach: Separate and Combine

Another way to implement priority sort is by separating priority and non-priority elements:

const prioritySortAlternative = (arr1, arr2) => {
    const priority = arr1.filter(item => arr2.includes(item)).sort((a, b) => a - b);
    const nonPriority = arr1.filter(item => !arr2.includes(item)).sort((a, b) => a - b);
    return [...priority, ...nonPriority];
};

const arr1 = [5, 4, 3, 2, 1];
const arr2 = [2, 3];

const result = prioritySortAlternative(arr1, arr2);
console.log(result);
[ 2, 3, 1, 4, 5 ]

Comparison

Method Modifies Original? Time Complexity Readability
Custom Sorter Yes O(n log n) Medium
Separate & Combine No O(n log n) High

Conclusion

Priority sort allows you to maintain order while giving precedence to specific elements. The custom sorter approach modifies the original array, while the separate-and-combine method preserves it and returns a new sorted array.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements