2017-04-06 93 views
0

假设我有一个巨大的数组(100K记录)集合可以说(sourceArray)。我有一个另一个数组的列表(matchIds)我需要使用从这个sourceArray过滤。我如何用lodash实现这一目标?或纯JavaScript?如何使用集合作为谓词来过滤数组

var sourceArray = [{ 
    "id": 123, 
    }, 
    { 
    "id": 456 
    }, 
    { 
    "id": 789 
    }, 
    { 
    "id": 111 
    }, 
    { 
    "id": 222 
    }, 
    { 
    "id": 333 
    }]; 


var matchIds = [123, 222]; 

下面的过滤器只针对单一项目

console.log(
     _.filter(sourceArray, function(arr){ 
     return arr.id === 123; 
     }) 
    ); 

http://jsbin.com/fegipuwuwa/1/edit?html,js,console

什么我真的希望是arr.id <..in..> matchIds

回答

0

那么您的谓词数据结构不是最优的,并且会通过增加尺寸来负面影响整体性能。如果您首先将[123, 222]转换为散列或地图,那将是最好的。一旦完成,剩下的只是O(n)。

var matchIds = [123, 222], 
 
     hash = matchIds.reduce((h,id) => (h[id] = true, h),{}) 
 
sourceArray = [{ 
 
    "id": 123, 
 
    }, 
 
    { 
 
    "id": 456 
 
    }, 
 
    { 
 
    "id": 789 
 
    }, 
 
    { 
 
    "id": 111 
 
    }, 
 
    { 
 
    "id": 222 
 
    }, 
 
    { 
 
    "id": 333 
 
    }]; 
 
     result = sourceArray.filter(o => hash[o.id]); 
 
console.log(result);

+0

matchIds将是最大。 20个ID ..只有sourceArray是巨大的(有时100K到150K) – FakirTrappedInCode

+0

@FakirTrappedInCode所以...这将使您从制作超过20个项目的150K索引中总结出3M浪费的操作。 – Redu

+0

谢谢。假设matchIds = [123,222,999,1111],我只返回999,1111。正如我所看到的Iam实际上只对这些不匹配的ID感兴趣,因为我会再调用另一个API来返回这些ID的响应.. – FakirTrappedInCode

3

为什么不干脆

var matchingArray = sourceArray.filter(function(item){ 
    return matchIds.indexOf(item.id) != -1 
}); 
匹配

这将返回匹配的所有项目matchIds