0

So let me preface this with the fact that I'm doing this coding in Codecademy so maybe its just that being weird.

I am trying to remove all punctuation from an array (dupBW) and set everything to lowercase.

My code works fine within the forEach, the console.log shows that. But then dupBW is unaffected when I log it out at the end.

Thanks for the help.

  dupBW.forEach(dupWord => {
    if(puncArray.includes(dupWord[dupWord.length-1])) {
      dupWord = dupWord.slice(0, dupWord.length-1);
      dupWord = dupWord.toLowerCase();
      console.log(dupWord);
    }
  });
  
  console.log(dupBW.join(' '));
4
  • 2
    What you’re looking for is probably Array.prototype.map, by returning dupWord in the callback. In foreach you’re not assigning it to anything. Commented Jan 12, 2021 at 11:57
  • Wouldn't it be easier to use String.prototype.replace() with a RegExp to match the punctuation? Commented Jan 12, 2021 at 11:57
  • 1
    dupWord is a copy of the string at the current index in dupBW. Modifying that copy doesn't affect the content of dupBW. Commented Jan 12, 2021 at 12:00
  • @Andreas What's more, you cannot modify strings at all, the only thing that's modified in the code is the dupWord local variable. Commented Jan 12, 2021 at 12:05

2 Answers 2

0

Change forEach to map and return dupWord at the end, and it will work; by assigning the array to the newly returned one. Array.prototype.map returns a new array with the return values of the callbacks.

dupBW = dupBW.map(dupWord => {
    if(puncArray.includes(dupWord[dupWord.length-1])) {
      dupWord = dupWord.slice(0, dupWord.length-1);
      dupWord = dupWord.toLowerCase();
      console.log(dupWord);
    }
      return dupWord;
  });
  
  console.log(dupBW.join(' '));
Sign up to request clarification or add additional context in comments.

1 Comment

map does not mutate original array. It creates a new array, that you assign to the same variable dupBW (assuming it was not declared with const).
0

If you see in the documentation for .forEach() you will find that forEach does not modify the array it is called on. For that, you can use regular for loop or map or reduce.

You can do the following,

let res = dupBW.map(dupWord => {
    if(puncArray.includes(dupWord[dupWord.length-1])) {
      dupWord = dupWord.slice(0, dupWord.length-1);
      dupWord = dupWord.toLowerCase();
      console.log(dupWord);
    }
    return dupWord;
  });
  
  console.log(res.join(' '));

2 Comments

"that forEach should not update" - It does not modify the array it is called on. But no-one is stopping you from doing it "by hand": .forEach((dupWord, index) => { ... dupBW[index] = dupWord; })
Agreed. @Andreas. My bad. Updating.

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.