Skip to content
Advertisement

looping through two array to replace one value in array for specific match

I’ve two arrays like below

flag: true
firstName: "user1"
lastName: "usr1"

flag: true
firstName: "user2"
lastName: "usr2"

flag: true
firstName: "user3"
lastName: "usr3"

And the other one like below

"user1"
"user2"

My intention is, the second array value matches the first array with firstname then needs to override flag with false.

I’m expecting a result like

flag: false
firstName: "user1"
lastName: "usr1"

flag: false
firstName: "user2"
lastName: "usr2"

flag: true
firstName: "user3"
lastName: "usr3"

Note: If firstname is not matched. I don’t want to change the flag value. –

Any good way to achieve this in react, Thanks

Advertisement

Answer

consider:

array 1 = users

array 2 = userNames

Then: This one will change the flag to true if user.firstName exist in userNames, else to false

users.map((user) => ({...user, flag: !userNames.includes(user.firstName)}))

This will return you the new array

If you do not want to change the flag if firstName does not match, then:

users.map((user) => userNames.includes(user.firstName) ? ({...user, flag: false}) : user)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement