[英]Filter an array by comparing its property value with another array in angular/typescript
I have two arrays我有两个数组
//1st one
tasks.push({ ID: 1, Address: "---", Latitude: 312313, Longitude: 21312 });
tasks.push({ ID: 3, Address: "---", Latitude: 312313, Longitude: 21312 });
//2nd one
agentTasks.push({ID:2,AgentID: 2,TaskID:1});
Now I want to filter tasks
array to get only those values which are not included in agentTasks
array.现在我想过滤
tasks
数组以仅获取那些未包含在agentTasks
数组中的值。 Like task id 1 is included in agentTasks
but 3 is not included.就像任务 id 1 包含在
agentTasks
但不包含 3。 So I want ID 3 value only.所以我只想要 ID 3 值。 How can I do this in angular/typescript?
我怎样才能在角度/打字稿中做到这一点?
You could create a Set of all TaskIDs from agentTasks
and then use .filter()
on the tasks
array to keep only those tasks which ID
doesn't exist in the set of TaskIds:您可以创建一个集所有TaskID的的
agentTasks
然后用.filter()
上的tasks
阵列只保留那些任务ID
不设定TaskID的存在:
const tasks = [ { ID: 1, Address: "---", Latitude: 312313, Longitude: 21312 }, { ID: 3, Address: "---", Latitude: 312313, Longitude: 21312} ]; const agentTasks = [{ID:2,AgentID: 2,TaskID:1}]; const taskIds = new Set(agentTasks.map(({TaskID}) => TaskID)); const res = tasks.filter(({ID}) => !taskIds.has(ID)); console.log(res);
Ultimately you want to use the filter
array function.最终您要使用
filter
数组函数。
The simplest approach is to search the agentTasks
array for each item in tasks
.最简单的方法是搜索
agentTasks
数组中的每一项tasks
。 This is fine for small arrays, but inefficient for larger arrays.这对于小数组来说很好,但对于较大的数组效率低下。
Instead, I would create a Map
from the agentTasks
array, using TaskID
as the key.相反,我将从
agentTasks
数组创建一个Map
,使用TaskID
作为键。 You can then filter tasks
based on whether or not they have a corresponding key in the Map
.然后,您可以根据
tasks
在Map
是否有相应的键来过滤tasks
。
//1st one const tasks = []; tasks.push({ ID: 1, Address: "---", Latitude: 312313, Longitude: 21312 }); tasks.push({ ID: 3, Address: "---", Latitude: 312313, Longitude: 21312 }); //2nd one const agentTasks = []; agentTasks.push({ID:2,AgentID: 2,TaskID:1}); const agentTasksMap = new Map(agentTasks.map(x => [x.TaskID, x])); const filtered = tasks.filter(task => !agentTasksMap.has(task.ID)); console.log(filtered);
Edit: The answer using Set
is better, since you don't care about the values in the Map
in my answer - you only care about the existence of a key.编辑:使用
Set
的答案更好,因为您不关心我的答案中Map
中的值 - 您只关心键的存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.