I have array of object and array, get the not matching array in javascript
for given array object arrobj and array arr
if clientid of arrobj has value in arr,
return not matching values on array from arr
I tried
const result = arrobj.find(mem => arr.includes(mem.clientId))
var arrobj = [
{
"caseTaskId": 207,
"clientId": 7831
},
{
"caseTaskId": 207,
"clientId": 7833
},
{
"caseTaskId": 207,
"clientId": 7834
}
]
var arr = [7834,7832]
Expected Output
[7832]
CodePudding user response:
SOLUTION 1
You can make use of Set, Array.prototype.map and Array.prototype.filter here as:
set will contain all arrobj's clientId. So all you have to do is to loop over arr and then filter out the not present id.
var arrobj = [
{
caseTaskId: 207,
clientId: 7831,
},
{
caseTaskId: 207,
clientId: 7833,
},
{
caseTaskId: 207,
clientId: 7834,
},
];
var arr = [7834, 7832];
const set = new Set(arrobj.map((o) => o.clientId));
const result = arr.filter((no) => !set.has(no));
console.log(result);
SOLUTION 2
You can also use Array.prototype.find here as:
var arrobj = [
{
caseTaskId: 207,
clientId: 7831,
},
{
caseTaskId: 207,
clientId: 7833,
},
{
caseTaskId: 207,
clientId: 7834,
},
];
var arr = [7834, 7832];
const result = arr.filter((no) => !arrobj.find((o) => o.clientId === no));
console.log(result);
CodePudding user response:
Another option with for loops and Array.splice()
// Data
const arrobj = [
{
"caseTaskId": 207,
"clientId": 7831
},
{
"caseTaskId": 207,
"clientId": 7833
},
{
"caseTaskId": 207,
"clientId": 7834
}
];
const arr = [7834,7832];
// Loop in loop
for(let i = 0; i <= arr.length; i ) for(el of arrobj) if(arr[i] == el.clientId) arr.splice(i, 1);
// Test
console.log(arr);
