Skip to content Skip to sidebar Skip to footer

Javascript Map Function - Pass Word-items To A Function To Return Html Element

After finding the most used words, I pass the most used word to this alterText function too alter the word export default function alterText(txtArr, mostUsedWord, firstWord, lastW

Solution 1:

You need to return a value in a map function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

I would also try to avoid using the same variable name in multiple scope levels, in this case word. It's not terribly accurate or descriptive if you think about it and can lead to bugs. Try to think of more descriptive variable names.

const word = mostUsedWord.map(mostUsedWord => {
  return `<span class="foo">${firstWord}</span><span class="word">${mostUsedWord}</span><span class="bar">${lastWord}</span>`
})

One strategy that has helped me with these kinds of problems in the past, and to be quite honest, still helps me, is trying to split problems into component problems. Then, when something goes wrong, you have a smaller thing to work on. At this level you can open up the Javascript console in your web browser or perhaps even the Node run time to play around or test what is going wrong.

Post a Comment for "Javascript Map Function - Pass Word-items To A Function To Return Html Element"