Home > database >  Javascript : Check array element contains element from another array
Javascript : Check array element contains element from another array

Time:11-24

I have below array -

Array(12)
[
{username:"abc" , userpid:"M123"},
{username:"xyz" , userpid:"T234"},
{username:"mnp" , userpid:"L678"}
.
.
]

I have another array as -

Array (6)
    [
    {projectname:"corporate" , projecttype:"oil" userpid:"M123"},
    {projectname:"corporate" , projecttype:"oil" userpid:"K123"},
    {projectname:"corporate" , projecttype:"oil" userpid:"P123"},
    .
    .
    ]

Here , I wanted to filter out all the elements from first array whose userpid is not in second array. Eg. userpid M123 is present in second array thats why output -

[
{username:"xyz" , userpid:"T234"},
{username:"mnp" , userpid:"L678"}
]

I tried with - 

array1.some(x=>x.userpid!=(array2.filter(y=>y.userpid)))

But this is giving syntax error.

CodePudding user response:

Something like this

const arr1 = [
{username:"abc" , userpid:"M123"},
{username:"xyz" , userpid:"T234"},
{username:"mnp" , userpid:"L678"}];

const arr2 = [
    {projectname:"corporate", projecttype:"oil", userpid:"M123"},
    {projectname:"corporate", projecttype:"oil", userpid:"K123"},
    {projectname:"corporate", projecttype:"oil", userpid:"P123"},];

const result = arr1.filter(item => !arr2.some(v => item.userpid === v.userpid));

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related