Call indexOf() when creating an array using the .map() method

Hello, I am new to the forums here. I’d like to say that I’m happy to be part of this community of fellow developers.

Working on a project, the Mini Linter (Introduction to JavaScript) I was typing a function using the .map() method when I encountered a problem.

What I want to do is: make a new array, which should be the copy of the storyWords array. But it should show a blank space “____” in place of the words really, very and basically, when they are used more than one time.

Here it is:

let test = storyWords.map( word => {
  if ( word == "really" || word == "very" || word == "basically" ) {
    if ( test.indexOf(word) == -1 ) {
          return "___";
    }
  } else return word;
})

I get this error: ReferenceError: test is not defined
at storyWords.map.word

Can anyone please let me know what I am doing wrong? Thank you in advance.

test is the variable you use to store the result of .map(), but while the function is running, this variable isn’t yet defined.

why would you want to use .indexOf? if word equals one of the words you want to filter, you can simple return the underscores.

.map() constructs a new array based of the returned values

more about map here:

https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The thing is: I’d like to return these words just one time, and any other time they occur I want them to be replaced by the underscores.

That is precisely what map does? You can return the value you want to have in the new array. So based on the current word, you either return the word or the censored (underscore) string.

You don’t need .indexOf.

I’m not sure this solves the problem, I’ll keep playing with the code and see what happens. Thank you for using your time to answer my question :slightly_smiling_face:.

map enable us to mutate any item we like:

console.log(['hello', 'world'].map(function(item){
  return item === 'hello' ? '*****' : item;
}))

I will stick to your suggestion and use the map function to just return “___” whenever one of these words will be iterated over.

let test = storyWords.map( word => {
  if ( word == "really" || word == "very" || word == "basically" ) {
          return "___";
    }
   else return word;
})

Thanks again

Good idea, or do you still preferable do something differently?

I’m always eager to learn new ways to perform usual actions, like returning words from an array, but for now this map() method will just do.

I will read some more documentation and we’ll see what I find there too.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.