I'm writing a React script where I have to map through a string inside a map function.
const set = new Set(["I", "deck", " Yes."]);
const arr = value.sort((a, b) => a.id - b.id)
var v = 0
return <RightWrapper>
<Header>
<Button onClick={handleDelete}>Delete Transcription</Button>
<Button onClick={signOut}>Sign out</Button>
</Header>
{
arr.map(transcript => (
transcript.Transcription.map(word => (
<p key={transcript.id}
style={{
color: set.has(word) ? 'red' : 'black'
}}
>{transcript.createdAt + " " + transcript.Transcription + " "} </p>
))
)
)
}
</RightWrapper>;
Objective - to check if any word inside the string transcript.Transcription is in the set. If yes then highlight that word.
transcript.Transcription is a sentence(string)
There are probably other ways of doing it, but this is what I could come up with the information you have provided:
[OPTIONAL] Use arrays if possible (because there is a built-in some function that checks if at least one object in the array satisfies a given condition)
I am converting the reference words (I call them "keywords" in the below example) into a Regular Expression, and I invoke the test method on these
For the input words that return true you could use your styling logic and apply the necessary styles.
// const keywords = ["I", "Programmer"]
const keywords = new Set(["I", "Programmer"])
const inputWords = ["I am a Programmer", "He is a Programmer", "She was a coder", "Yes, I love JS"]
function hasMatch(word, keywords) {
for (let kw of keywords) {
let regex = new RegExp(kw)
if (regex.test(word)) return true
}
return false
}
inputWords.forEach(word => console.log(`${word} --> ${hasMatch(word, keywords)}`))
if (inputWords.some(word => hasMatch(word, keywords))) {
console.log('Found at least one match!')
}
NOTE: The regex is case-sensitive. You could make it insensitive by adding an extra parameter i to its constructor