Sort array by order according to another array

后端 未结 6 1481
谎友^
谎友^ 2021-02-09 14:49

I have an object that is being returned from a database like this: [{id:1},{id:2},{id:3}]. I have another array which specified the order the first array should be

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 15:16

    In your example, the objects are initially sorted by id, which makes the task pretty easy. But if this is not true in general, you can still sort the objects in linear time according to your array of id values.

    The idea is to first make an index that maps each id value to its position, and then to insert each object in the desired position by looking up its id value in the index. This requires iterating over two arrays of length n, resulting in an overall runtime of O(n), or linear time. There is no asymptotically faster runtime because it takes linear time just 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) {  // Get the position of each sorted key.
        index[sortedKeys[i]] = i;
      }
      var sorted = new Array(n);
      for (var i = 0; i < n; ++i) {  // Look up each object key in the index.
        sorted[index[objects[i][keyName]]] = objects[i];
      }
      return sorted;
    }
    
    var objects = [{id: 'Tweety', animal: 'bird'},
                   {id: 'Mickey', animal: 'mouse'},
                   {id: 'Sylvester', animal: 'cat'}],
        sortedIds = ['Tweety', 'Mickey', 'Sylvester'];
    
    var sortedObjects = objectsSortedBy(objects, 'id', sortedIds);
    
    // Check the result.
    for (var i = 0; i < sortedObjects.length; ++i) {
      document.write('id: '+sortedObjects[i].id+', animal: '+sortedObjects[i].animal+'
    '); }

提交回复
热议问题