2017-04-06 73 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