基于外部数组的Lodash排序集合

sil*_*zir 19 javascript arrays collections underscore.js lodash

我有一个像这样的键的数组:

['asdf12','39342aa','12399','129asg',...] 
Run Code Online (Sandbox Code Playgroud)

以及在每个对象中都有这些键的集合,如下所示:

[{guid: '39342aa', name: 'John'},{guid: '129asg', name: 'Mary'}, ... ]
Run Code Online (Sandbox Code Playgroud)

是否有一种快速的方法可以根据第一个数组中键的顺序对集合进行排序?

idb*_*old 43

var sortedCollection = _.sortBy(collection, function(item){
  return firstArray.indexOf(item.guid)
});
Run Code Online (Sandbox Code Playgroud)

  • @silintzir您在问题中要求“一种对集合进行排序的快速方法”。但如果您真正关注的是运行时性能,这并不是一个快速的方法。 (2认同)
  • 这非常有效,是我找到的最优雅的解决方案 (2认同)

Alv*_*aro 9

如果您想将不匹配的元素放在 sortedCollection 的末尾而不是开头,这里只是对已接受答案的简单添加:

const last = collection.length;

var sortedCollection = _.sortBy(collection, function(item) {
  return firstArray.indexOf(item.guid) !== -1? firstArray.indexOf(item.guid) : last;
});
Run Code Online (Sandbox Code Playgroud)

  • 尽管这不是公认的答案,但对我来说确实如此,因为将未知元素放在数组的末尾(所有已排序的项目之后)而不是开头似乎更自然 (3认同)

the*_*eye 7

输入:

var data1 = ['129asg', '39342aa'];
var data2 = [{
    guid: '39342aa',
    name: 'John'
}, {
    guid: '129asg',
    name: 'Mary'
}];
Run Code Online (Sandbox Code Playgroud)
  1. 首先创建一个索引对象_.reduce,就像这样

    var indexObject = _.reduce(data2, function(result, currentObject) {
        result[currentObject.guid] = currentObject;
        return result;
    }, {});
    
    Run Code Online (Sandbox Code Playgroud)
  2. 然后map是第一个数组中带有对象的项目indexObject,就像这样

    console.log(_.map(data1, function(currentGUID) {
        return indexObject[currentGUID]
    }));
    
    Run Code Online (Sandbox Code Playgroud)

产量

[ { guid: '129asg', name: 'Mary' },
  { guid: '39342aa', name: 'John' } ]
Run Code Online (Sandbox Code Playgroud)

注意:如果要对这么多对象进行排序,这种方法会非常有效,因为它会减少第二个数组中的线性查找,从而使整个逻辑以O(M*N)时间复杂度运行.