In your example, the objects are first sorted using id , which makes the task pretty simple. But if that is not the case at all, you can sort the objects by linear time according to your array of id values.
The idea is to first create an index that maps each id value to its position, and then insert each object at the desired position by looking at its id value in the index. This requires iteration over two arrays of length n , which leads to a total execution time of O(n) or linear time. There is no asymptotically faster operation, because it takes linear time to read the input array.
function objectsSortedBy(objects, keyName, sortedKeys) { var n = objects.length, index = new Array(n); for (var i = 0; i < n; ++i) {
source share