I have two array of objects,arr1
and arr2
if taskId
and id
same then retreive from arr1
How to check based on property from arr1 and arr2 in javascript
var arr1= [
{"name":"refresh task","memberIds":[981],"dueOn":"2022-08-30","taskId":19},
{"name":"ref one","memberIds":[981,982],"dueOn":"2022-08-25","taskId":null}
]
var arr2 =[
{
"country": "IN",
"tasks": [
{id: 19, "name": "abc" },
{id: 20, "name": "xyz" }
]
}
]
I tried
var result = arr1.filter(e=>e.taskId===(arr2.map(i=>i.tasks.map(t=>t.id))
Expected Output
[
{"name":"refresh task","memberIds":[981],"dueOn":"2022-08-30","taskId":19}
]
CodePudding user response:
- Using
Set
,Array#flatMap
, and[
Array#map][3], get the list of task ids in
arr2`` - Using
Array#filter
, andSet#has
, return the resulting array wheretaskId
is in the above set
const
arr1= [
{"name":"refresh task", "memberIds":[981], "dueOn":"2022-08-30", "taskId":19},
{"name":"ref one", "memberIds":[981,982], "dueOn":"2022-08-25", "taskId":null}
],
arr2 =[
{
"country": "IN",
"tasks": [ {"id": 19, "name": "abc"}, {"id": 20, "name": "xyz"} ]
}
];
const taskIdSet = new Set(
arr2.flatMap(({ tasks = [] }) => tasks.map(({ id }) => id))
);
const result = arr1.filter(({ taskId }) => taskIdSet.has(taskId));
console.log(result);
EDIT: To get "I have two arrays of objects, arr1, and arr2 if taskId and id not same then retrieve from arr2":
const
arr1= [
{"name":"refresh task", "memberIds":[981], "dueOn":"2022-08-30", "taskId":19},
{"name":"ref one", "memberIds":[981,982], "dueOn":"2022-08-25", "taskId":null}
],
arr2 =[
{
"country": "IN",
"tasks": [ {"id": 19, "name": "abc"}, {"id": 20, "name": "xyz"} ]
}
];
const taskIdSet = arr1.reduce((taskIdSet, { taskId }) => {
if(taskId !== null) { taskIdSet.add(taskId); }
return taskIdSet;
}, new Set);
const result = arr2
.flatMap(({ tasks = [] }) => tasks)
.filter(({ id }) => !taskIdSet.has(id));
console.log(result);
CodePudding user response:
This works too:
var result = arr1.filter(e=>{
for(let obj of arr2){
for(let task of obj.tasks){
return e.taskId === task.id;
}
}
})