Lodash sort collection based on external array

前端 未结 5 718
名媛妹妹
名媛妹妹 2020-12-30 21:01

I have an array with keys like so:

[\'asdf12\',\'39342aa\',\'12399\',\'129asg\',...] 

and a collection which has these keys in each object

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 21:42

    Input:

    var data1 = ['129asg', '39342aa'];
    var data2 = [{
        guid: '39342aa',
        name: 'John'
    }, {
        guid: '129asg',
        name: 'Mary'
    }];
    
    1. First create an index object, with _.reduce, like this

      var indexObject = _.reduce(data2, function(result, currentObject) {
          result[currentObject.guid] = currentObject;
          return result;
      }, {});
      
    2. And then map the items of the first array with the objects from the indexObject, like this

      console.log(_.map(data1, function(currentGUID) {
          return indexObject[currentGUID]
      }));
      

    Output

    [ { guid: '129asg', name: 'Mary' },
      { guid: '39342aa', name: 'John' } ]
    

    Note: This method will be very efficient if you want to sort so many objects, because it will reduce the linear look-up in the second array which would make the entire logic run in O(M * N) time complexity.

提交回复
热议问题