使用Lodash或vanilla JS根据对象键过滤数组的最有效方法是什么?

问题描述:

我有对象的两个数组:使用Lodash或vanilla JS根据对象键过滤数组的最有效方法是什么?

array1 = [ 
    {id:1, name: 'one'}, 
    {id:4, name: 'four'} 
] 

array2 = [ 
    {id:1, name: 'one'}, 
    {id:2, name: 'two'}, 
    {id:3, name: 'three'}, 
    {id:5, name: 'five'}, 
    {id:6, name: 'six'}, 
    {id:7, name: 'seven'} 
] 

我想从array1谁的idarray2存在删除任何对象。

所以我期待的结果将是:

array1 = [ 
    {id:1, name:'one'} 
] 
+0

换句话说,你想找到两个数组之间的交集? https://*.com/questions/1885557/simplest-code-for-array-intersection-in-javascript –

+0

你有没有尝试过任一种方法呢? – stealththeninja

+1

你尝试过那种方式效率不高? – epascarello

使用lodash的_.intersectionBy()

var array1 = [ 
 
    {id:1, name: 'one'}, 
 
    {id:4, name: 'four'} 
 
]; 
 

 
array2 = [ 
 
    {id:1, name: 'one'}, 
 
    {id:2, name: 'two'}, 
 
    {id:3, name: 'three'}, 
 
    {id:5, name: 'five'}, 
 
    {id:6, name: 'six'}, 
 
    {id:7, name: 'seven'} 
 
]; 
 

 
var result = _.intersectionBy(array1, array2, 'id'); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

的快速性和可读性的办法是:

var referenceKeys = array2.map(function(entity) { return entity.id; }); 

var result = array1.filter(function(entity) { 
    return referenceKeys.indexOf(entity.id) !== -1; 
}); 

但不能保证它在所有维度的最快的。 (重复次数,数组1的长度,数组2的长度)。

+1

根据“高效”的含义,这可能不是一个好的解决方案,因为它是二次的。 –

您可以使用标准方法,通过使用哈希表,该哈希表对两个数组都使用一次迭代。

var array1 = [{ id: 1, name: 'one' }, { id: 4, name: 'four' }], 
 
    array2 = [{ id: 1, name: 'one' }, { id: 2, name: 'two' }, { id: 3, name: 'three' }, { id: 5, name: 'five' }, { id: 6, name: 'six' }, { id: 7, name: 'seven' }], 
 
    hash = Object.create(null), 
 
    result; 
 

 
array2.forEach(function (o) { 
 
    hash[o.id] = true; 
 
}); 
 

 
result = array1.filter(function (o) { 
 
    return hash[o.id]; 
 
}); 
 

 
console.log(result);

您可以使用此一Set

const seenIds = array2.reduce((set, o) => set.add(o.id), new Set()); 
const result = array1.filter(o => seenIds.has(o.id)); 
+0

'const seenIds = new Set(array2.map(o - > o.id));'稍微短一些。 :) – 2017-11-15 19:05:28