I’ve two arrays like below
JavaScript
x
12
12
1
flag: true
2
firstName: "user1"
3
lastName: "usr1"
4
5
flag: true
6
firstName: "user2"
7
lastName: "usr2"
8
9
flag: true
10
firstName: "user3"
11
lastName: "usr3"
12
And the other one like below
JavaScript
1
3
1
"user1"
2
"user2"
3
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
JavaScript
1
12
12
1
flag: false
2
firstName: "user1"
3
lastName: "usr1"
4
5
flag: false
6
firstName: "user2"
7
lastName: "usr2"
8
9
flag: true
10
firstName: "user3"
11
lastName: "usr3"
12
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
JavaScript
1
2
1
users.map((user) => ({user, flag: !userNames.includes(user.firstName)}))
2
This will return you the new array
If you do not want to change the flag if firstName does not match, then:
JavaScript
1
2
1
users.map((user) => userNames.includes(user.firstName) ? ({user, flag: false}) : user)
2