0

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

12 Comments

Lets check this
userNames.includes() will look for whole matching items, in this case they are objects. It won't work.
userNames are not objects?! They are strings
String array as far as I can parse the OP
You are not doing something right or your question is not clear. This should work if you have 2 arrays, one of them is array of objects and the second one is array of strings, index of elements does not matter. If an element from array 2 matches firstName of an object from array 1, it should change it to false, else to true. It returns a new array, not changing the first one
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.