2017-11-10 74 views
0

我有對象的兩個數組:使用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://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript –

+0

你有沒有嘗試過任一種方法呢? – stealththeninja

+1

你嘗試過那種方式效率不高? – epascarello

回答

2

使用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>

1

的快速性和可讀性的辦法是:

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

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

但不能保證它在所有維度的最快的。 (重複次數,數組1的長度,數組2的長度)。

+1

根據「高效」的含義,這可能不是一個好的解決方案,因爲它是二次的。 –

0

您可以使用標準方法,通過使用哈希表,該哈希表對兩個數組都使用一次迭代。

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);

0

您可以使用此一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

相關問題