neowenshun
neowenshun

Reputation: 960

reactjs how to filter / check if a any object in an array is present in another array of objects?

im facing the issue when trying to implement some conditional rendering. Here is the context:

the data:

groups_a : [
             {id:1} ,
             {id:2}
            ]

groups_b : [
             {id:1} ,
             {id:3}
            ]

The condition:

I wish to be check each item in groups_b , whether they exist in groups_a . So in this case , the condition should return back true because groups_b has id:1 and so does groups_a

JSX :

            {###the condition ##
                         ?
            <Button>Approve</Button>   
            :
            null
            } 

Upvotes: 3

Views: 1666

Answers (3)

ehab
ehab

Reputation: 8024

You could do this assuming groupA/groupB to be array of object

const groupA = [{id:1}, {id:3}, {id:4}];
const groupB = [{id:1}, {id:3}];

const boolean = groupB.every(obj => groupA.find(aObj => obj.id === aObj.id));
console.log('Method 1:', boolean)
// this will be true if every object in B is included in A

// If these are extremely large arrays you can improve performance by converting groupA into obj, and then checking by that object

const groupAHashMap = groupA.reduce((acc, cur) => ({...acc, [cur.id]: true}), {});
const boolean2 = groupB.every(obj => groupAHashMap[obj.id]);
console.log('Method 2:', boolean2)

Upvotes: 4

Hamid Shoja
Hamid Shoja

Reputation: 4768

it's an other solution that you can get the common list also.

const groupA = [{id:1}, {id:3}, {id:4}];
const groupB = [{id:1}, {id:2}];



const ListCommon = groupA.filter(x => groupB.find(y => x.id === y.id));

console.log('result:', ListCommon.length>0)
console.log('List:', ListCommon)

Upvotes: 0

Ali Faris
Ali Faris

Reputation: 18592

checkout this

function App(){ 

    const groupA = [{id:1}, {id:2}];
    const groupB = [{id:1}, {id:3}];

    const gourpAIds = groupA.map(item => item.id);

    return groupB.map(item => {
        if(gourpAIds.includes(item.id)){
            return <Button>Approve</Button>   ;
        }else{
            return null;
        }
    });

}

Upvotes: 0

Related Questions