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)
如果您想将不匹配的元素放在 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)
输入:
var data1 = ['129asg', '39342aa'];
var data2 = [{
guid: '39342aa',
name: 'John'
}, {
guid: '129asg',
name: 'Mary'
}];
Run Code Online (Sandbox Code Playgroud)
首先创建一个索引对象_.reduce
,就像这样
var indexObject = _.reduce(data2, function(result, currentObject) {
result[currentObject.guid] = currentObject;
return result;
}, {});
Run Code Online (Sandbox Code Playgroud)然后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)时间复杂度运行.
归档时间: |
|
查看次数: |
8067 次 |
最近记录: |