问题描述
我有两个对象数组,一个大约有.1800 个项目,第二个大约.600 项.每个数组中的数据示例:
I have two arrays of objects, one with approx. 1800 items and the second with approx. 600 items. An example of the data in each array:
let exampleArray = [{ID:X2346,NAME:"someName"},{ID:X8847,NAME:"someName2"},...]
我需要比较两个数组,如果大数组中某个对象的 'ID' 值等于小数组中某个对象的 ID 值,则将该对象从大数组中完全移除,或者离开较大的数组,仅包含基于属性ID"的较小数组中不存在的对象.
I need to compare the two arrays, and if the 'ID' value from an object in the large array is equal to the ID value from an object in the smaller array, remove the object entirely from the larger array, or leave the larger array with only objects that don't exist in the smaller array based on property 'ID'.
我使用两个嵌套的 for 循环完成了此操作,并且它有效,但我正在尝试提高速度.我已经阅读了哈希表,但我认为它不适用于这种情况,或者我不完全了解如何使用它们.有没有更快的方法来实现我的目标?
I have done this using two nested for loops, and it works, but I'm trying to improve the speed. I've read up on hash tables but I don't think it can apply to this situation or I am not fully understanding how to use them. Is there a faster way to accomplish my goal?
for (let x=0;x<largeArray.length;x++){
for (let y=0;y<smallerArray.length;y++){
if(largeArray[x]['ID']===smallerArray[y]['ID']){
largeArray.splice(x,1)
}
}
}
推荐答案
你可以用Array.prototype.map()
映射小数组中的所有ID:
You can map all the IDs in the small array with Array.prototype.map()
:
const idsFilter = smallArray.map(item => item.ID);
然后你可以使用它从大数组中过滤掉ID包含在idsFilter
中的项目,使用Array.prototype.filter()
:
then you can use it to filter out from the large array the items whose ID is included in idsFilter
, using Array.prototype.filter()
:
const filteredLargeArray = largeArray.filter(item => !idsFilter.includes(item.ID));
这篇关于从数组中查找和删除具有相同属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!