Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sort object array based on another array of keys - JavaScript
When working with arrays of objects in JavaScript, you may need to sort one array based on the order defined in another array. This is particularly useful when you have a reference array that defines the desired sorting order.
Problem Statement
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("Original arrays:");
console.log("arr1:", arr1);
console.log("arr2:", arr2);
Original arrays:
arr1: [ 'd', 'a', 'b', 'c' ]
arr2: [ { a: 1 }, { c: 3 }, { d: 4 }, { b: 2 } ]
We need to sort the second array according to the order of elements in the first array. The expected output should be:
[{d:4},{a:1},{b:2},{c:3}]
Solution Using Array.sort() and indexOf()
We can solve this by using the sort() method with a custom comparator that uses indexOf() to determine the order:
const arr1 = ['d','a','b','c'];
const arr2 = [{a:1},{c:3},{d:4},{b:2}];
const sortArray = (referenceArray, objectArray) => {
objectArray.sort((a, b) => {
const aKey = Object.keys(a)[0];
const bKey = Object.keys(b)[0];
return referenceArray.indexOf(aKey) - referenceArray.indexOf(bKey);
});
};
sortArray(arr1, arr2);
console.log("Sorted array:", arr2);
Sorted array: [ { d: 4 }, { a: 1 }, { b: 2 }, { c: 3 } ]
How It Works
The sorting algorithm works by:
- Extracting the first (and only) key from each object using
Object.keys()[0] - Finding the position of each key in the reference array using
indexOf() - Comparing positions to determine the sort order
Alternative Solution with Map for Better Performance
For larger arrays, we can optimize performance by creating a position map:
const arr1 = ['d','a','b','c'];
const arr2 = [{a:1},{c:3},{d:4},{b:2}];
const sortArrayOptimized = (referenceArray, objectArray) => {
// Create position map for O(1) lookup
const positionMap = new Map();
referenceArray.forEach((item, index) => {
positionMap.set(item, index);
});
objectArray.sort((a, b) => {
const aKey = Object.keys(a)[0];
const bKey = Object.keys(b)[0];
return positionMap.get(aKey) - positionMap.get(bKey);
});
};
// Reset array for demonstration
const arr2Copy = [{a:1},{c:3},{d:4},{b:2}];
sortArrayOptimized(arr1, arr2Copy);
console.log("Optimized sorted array:", arr2Copy);
Optimized sorted array: [ { d: 4 }, { a: 1 }, { b: 2 }, { c: 3 } ]
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| indexOf() approach | O(n² log n) | Small arrays |
| Map-based approach | O(n log n) | Large arrays |
Conclusion
Both approaches effectively sort an object array based on a reference array's order. Use the indexOf method for simplicity with small datasets, or the Map-based approach for better performance with larger arrays.
