Sort an array according to another array in JavaScript

When working with arrays in JavaScript, you may need to sort one array based on the order of elements in another array. This is useful when you have a reference array that defines the desired ordering.

Suppose we have two arrays like these:

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

console.log("Original arr1:", arr1);
console.log("Reference arr2:", arr2);
Original arr1: [ 1, 3, 2, 4, 5, 6 ]
Reference arr2: [ 1, 2, 5 ]

We want to sort arr1 so that elements appearing in both arrays come first (in the order they appear in arr2), followed by remaining elements from arr1 in their original order.

Using Custom Sort Function

We can create a sorting function that prioritizes elements based on their presence in the reference array:

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

const sortByReference = (arr1, arr2) => {
    const inBoth = el => arr1.indexOf(el) !== -1 && arr2.indexOf(el) !== -1;
    
    const sorter = (a, b) => {
        // If both elements are in reference array, sort by reference order
        if(inBoth(a) && inBoth(b)){
            return arr2.indexOf(a) - arr2.indexOf(b);
        }
        // If only 'a' is in reference, it comes first
        if(inBoth(a)){
            return -1;
        }
        // If only 'b' is in reference, it comes first
        if(inBoth(b)){
            return 1;
        }
        // If neither is in reference, maintain original order
        return 0;
    };
    
    arr1.sort(sorter);
};

sortByReference(arr1, arr2);
console.log("Sorted arr1:", arr1);
Sorted arr1: [ 1, 2, 5, 3, 4, 6 ]

Alternative Approach Using Filter and Concat

Another approach is to separate the arrays and then combine them:

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

const sortByReferenceAlternate = (arr1, arr2) => {
    // Get elements from arr2 that exist in arr1
    const commonElements = arr2.filter(el => arr1.includes(el));
    
    // Get elements from arr1 that don't exist in arr2
    const uniqueElements = arr1.filter(el => !arr2.includes(el));
    
    return [...commonElements, ...uniqueElements];
};

const result = sortByReferenceAlternate(arr1, arr2);
console.log("Result:", result);
Result: [ 1, 2, 5, 3, 4, 6 ]

Comparison

Method Modifies Original Performance Readability
Custom Sort Yes O(n log n) Complex
Filter + Concat No O(n²) Simple

Conclusion

Both approaches effectively sort an array based on another array's order. The custom sort method modifies the original array, while the filter approach creates a new array. Choose based on whether you need to preserve the original array.

Updated on: 2026-03-15T23:19:00+05:30

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements