How do I sort an array of objects based on the ordering of another array?

前端 未结 8 562
滥情空心
滥情空心 2020-11-28 12:41

I have a list of objects:

[ { id: 4, name:\'alex\' }, { id: 3, name:\'jess\' }, { id: 9, name:\'...\' }, { id: 1, name:\'abc\' } ]

I have a

8条回答
  •  清酒与你
    2020-11-28 13:37

    Well, the simple answer would be, "for a set of data this small, anything less costly than an infinite loop will be basically unnoticeable." But let's try to answer this "right."

    There's no rhyme or reason to the order in the second array, it's just a list of foreign keys (to use SQL terminology) on the primary keys of the first array. So, thinking of them as keys, and that we want efficient lookup of those keys, a hash table (object) would probably "sort" this the quickest, in an O(n) fashion (2*n, really) assuming the first array is called objArray and the second array is called keyArray:

    // Create a temporary hash table to store the objects
    var tempObj = {};
    // Key each object by their respective id values
    for(var i = 0; i < objArray.length; i++) {
        tempObj[objArray[i].id] = objArray[i];
    }
    // Rebuild the objArray based on the order listed in the keyArray
    for(var i = 0; i < keyArray.length; i++) {
        objArray[i] = tempObj[keyArray[i]];
    }
    // Remove the temporary object (can't ``delete``)
    tempObj = undefined;
    

    And that should do it. I can't think of any method that doesn't require two passes. (Either one after the other, like this, or by passing multiple times through the array and spliceing out the found elements, which can get costly with backwards-sorted data, for instance.)

提交回复
热议问题