Home > Mobile >  How can I compare 2 array of objects, and return a new array ONLY containing properties that aren�
How can I compare 2 array of objects, and return a new array ONLY containing properties that aren�

Time:10-25

I have two array of objects with member information in them. Each object is mapped out to display the user information on screen. Each displayed user will have a checkbox next to it. When the checkbox is clicked, the user can delete the selected user from the database

The Issue: when a userObj checkbox is clicked, that userObj is added to an array named checkedIds. I somehow need to compare the original teamMembers array with the new checkedIds array. And return an array that has all the ID's EXCEPT the ID's that are in checkedIds

Note* The comparisons are based on the ID property. Note* I need the final array of ID's because that's what's expected in the backend

userObj -> {ID: userID, Name:userName, Email:userEmail}

checkedIds -> array of [userObjs] with a checked checkbox status
(this means all objects in this array have been marked for deletion.)

teamMembers -> an array of [userObjs] of all teamMembers currently in the database

// Process flow
teamMembers array -> 
[{ID: 45, Name:userName1, Email:userEmail1},
 {ID: 78 Name:userName2, Email:userEmail2},
 {ID: 2, Name:userName3, Email:userEmail3}
]
// These items are mapped in the react JSX to display the name and email on screen.
// And each mapped object will also display a checkbox

user clicks checkbox ->
// when a user clicks a checkbox to mark that userObj for deletion,
the actual object is copied to a new array called checkedIds
// now we have 2 array of objects checkedIds and teamMembers

Delete button is clicked
***// This is where I'm stuck***
// after the user checks the checkbox, and then presses the delete button,
I need to compare the two arrays. and return a new array that contains
only the ID's of the remaining objects, that is to say, all objects in
teamMembers that do not share the same ID as any of the objects in checkedIds 

EXPECTED OUTPUT:

teamMembers = 
[
{ID: 45, Name:userName1, Email:userEmail1},
 {ID: 78 Name:userName2, Email:userEmail2},
 {ID: 2, Name:userName3, Email:userEmail3}
]

checkedIds =
[
{ID: 45, Name:userName1, Email:userEmail1},
]

RETURNS -> 
fitlteredArr = 
[78,2]

CodePudding user response:

Something in lines of:

teamMembers.filter(({ ID }) => !checkedIds.map(x => x.ID).includes(ID))

enter image description here

  • Related