Sort the second array according to the elements of the first array in JavaScript

Suppose, we have two arrays like these ?

const arr1 = ['d','a','b','c'];
const arr2 = [{a:1},{c:3},{d:4},{b:2}];

console.log("First array:", arr1);
console.log("Second array:", arr2);
First array: [ 'd', 'a', 'b', 'c' ]
Second array: [ { a: 1 }, { c: 3 }, { d: 4 }, { b: 2 } ]

We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

We have to sort the keys of the second array according to the elements of the first array.

Therefore, the output should look like ?

[ { d: 4 }, { a: 1 }, { b: 2 }, { c: 3 } ]

Example

The code for this will be ?

const arr1 = ['d','a','b','c'];
const arr2 = [{a:1},{c:3},{d:4},{b:2}];

const sortArray = (arr1, arr2) => {
    arr2.sort((a, b) => {
        const aKey = Object.keys(a)[0];
        const bKey = Object.keys(b)[0];
        return arr1.indexOf(aKey) - arr1.indexOf(bKey);
    });
};

sortArray(arr1, arr2);
console.log("Sorted second array:", arr2);

Output

Sorted second array: [ { d: 4 }, { a: 1 }, { b: 2 }, { c: 3 } ]

How It Works

The function uses the sort() method with a custom comparator:

  • Object.keys(a)[0] extracts the first (and only) key from each object
  • arr1.indexOf() finds the position of each key in the reference array
  • The difference between indices determines the sort order
  • Objects are reordered based on their keys' positions in arr1

Alternative Approach Using Map

For better performance with larger arrays, you can create a position map:

const arr1 = ['d','a','b','c'];
const arr2 = [{a:1},{c:3},{d:4},{b:2}];

const sortArrayWithMap = (arr1, arr2) => {
    // Create position map for O(1) lookup
    const positionMap = new Map();
    arr1.forEach((item, index) => {
        positionMap.set(item, index);
    });
    
    arr2.sort((a, b) => {
        const aKey = Object.keys(a)[0];
        const bKey = Object.keys(b)[0];
        return positionMap.get(aKey) - positionMap.get(bKey);
    });
};

sortArrayWithMap(arr1, arr2);
console.log("Result with Map approach:", arr2);
Result with Map approach: [ { d: 4 }, { a: 1 }, { b: 2 }, { c: 3 } ]

Comparison

Method Time Complexity Best For
indexOf() O(n²) Small arrays
Map O(n log n) Large arrays

Conclusion

Both approaches sort the second array based on the first array's order. Use the Map approach for better performance with larger datasets, as it avoids repeated indexOf() calls.

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

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements