Is it possible that there are no consequences to alterations made in .forEach()?

Just a heads up, I'm currently coding in Codecademy which might be causing some quirks.

I've been working on a task to remove all punctuation from an array called dupBW and convert everything to lowercase.

Interestingly, my code appears to work fine within the forEach loop as indicated by console.log. However, when I check dupBW at the end, it seems unchanged.

Any assistance would be greatly appreciated.

  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(' '));

Answer №1

To make it work, replace forEach with map and return dupWord at the end by assigning the array to the newly returned one. Using Array.prototype.map will create a new array with the return values of the callbacks.

modifiedWords = modifiedWords.map(word => {
    if(punctuationMarks.includes(word[word.length-1])) {
      word = word.slice(0, word.length-1);
      word = word.toLowerCase();
      console.log(word);
    }
    return word;
});

console.log(modifiedWords.join(' '));

Answer №2

When referring to the documentation for .forEach(), it is noted that forEach does not alter the array it operates on. In order to modify the array, alternatives such as a regular for loop, map, or reduce can be used.

An example of this in action is shown below:

let newArr = myArr.map(item => {
    if(someCondition) {
      item = performActionOnItem(item);
      console.log(item);
    }
    return item;
  });
  
  console.log(newArr.join(' '));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to adjust the state value in Pinia within a Vue3 component test, and have an impact on the component?

When testing the component using pinia with vue-test-utils, I encountered difficulty in modifying the state value stored in pinia. Despite trying multiple methods, I was unable to achieve the desired result. The original component and store files are provi ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Steps to activate JavaScript upon selecting a dropdown menu item

My webpage has two dropdown boxes for car makes and models. I want all the models of a selected make to display in the next box. Currently, the models only show up when the dropdown is clicked using the code below. window.onmousedown = function(e){ th ...

Releasing the mouse button after dragging successfully without the use of any libraries

I have implemented a pure CSS snap scroll feature and now I need to determine the position of an element in relation to the viewport once the user stops dragging. However, I prefer not to rely on any complex libraries as I do not require any actual movemen ...

Are there any potential performance implications to passing an anonymous function as a prop?

Is it true that both anonymous functions and normal functions are recreated on every render? Since components are functions, is it necessary to recreate all functions every time they are called? And does using a normal function offer any performance improv ...

Transfer information from my class to a specific pathway

Currently, I am in the process of developing an application using Angular 2. My goal is to be able to send data from my class to a specific route within the application. Sample Code @RouteConfig([ { name: 'Slider', ...

Unusual Behavior Causing Error: 'RangeError: Invalid time value'

Currently, I am developing a straightforward timestamp API using Express. Essentially, when a user inputs a date in 'regular' format, the API displays a JSON object with both the Unix format and the normal format. Below is the pertinent section o ...

How can I prevent the text from overlapping the lines in a d3 forced graph?

I am currently working with an SVG that contains text positioned in the center of a large circle, connected to two smaller circles by a line. The formula I am using to obtain the line coordinates is as follows: x1={Math.max(radius, Math.min(heigh ...

Unable to process image upload due to setState not being recognized as a function in ReactJs

Attempting to implement an upload function using the cropper component. However, encountering an error when trying to set the state: Uncaught TypeError: this.setState is not a function at FileReader.reader.onload Component import React, { Component, P ...

Showing the image as a backdrop while scrolling through text

How can I create an effect that continuously displays the image while scrolling text in Internet Explorer without using position: sticky or position: fixed? var sticky = document.querySelector('.sticky-container'); var img = document.querySele ...

Add() function is not duplicating the formatting

I'm attempting to replicate the content below inside a DIV. <ul class="pie-legend"><li><span style="background-color:#0066CC"></span>10-0-1</li><li><span style="background-color:#33CC33&q ...

Issue: The npm module 'moment' cannot be located

My Meteor app works flawlessly on localhost, but when deployed to a remote heroku server, I encounter these errors. (I am following this) Any suggestions on how to resolve this issue? 2016-09-09T13:26:02.533532+00:00 heroku[web.1]: Starting process with ...

storing Java command line arguments in an array

Hello, I am a complete beginner in Java and I have run into an issue when trying to use command line arguments as an array. For example, I attempted to write this code: double[] a = Double.parseDouble(args[0]); but it returned an error saying "cannot con ...

Searching in a PHP 4 level deep multidimensional associative array for a specific value

Hey everyone! I have this multidimensional associative array and I'm looking to search within it. public static function userAccessArray() { return array( array( 'title' => 'General', 'ac ...

Tips for accessing API data on a standalone HTML page

I am in the process of developing a project that utilizes coingecko's cryptocurrency api. At the moment, I have successfully implemented a chart that showcases the top 100 highest ranking coins. I am now seeking advice on the most efficient method to ...

What is the best way to assign the "active" class to a navigation list item using JavaScript within Bootstrap 4?

Update: just to clarify, I'm working on activating the navbar button based on the current page. I have a navigation bar set up and I am trying to dynamically add an "active" class to the li element when you are on that specific page. However, for som ...

Guide on transferring binary image data to a JavaScript function

I have $comment->image_data as the binary data of the image and I want to pass this data to the imgclick() function. Attempting the method below, but encountering an unexpected token error. <img src="data:image/jpg;base64,'.$comment->image_t ...

When the image is clicked, an email notification should be received confirming that the image has been clicked

I'm a beginner in the world of PHP and AJAX, and I'm having trouble receiving emails. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"> function trigger() { $.ajax({ type: "POST", ...

Discover the position of characters within a given string

I'm trying to accomplish a task similar to this: If the array [ "a", "b", "c" ] includes any of the characters in the constant word = "abracadabra", I want to retrieve that character along with its position in const word. My attempt so far looks lik ...

Querying the field's object type in MongoDB

My database contains records with a field that has different data types in each record. I would like to query only for the records where this field contains strings. Is there a way to search for specific data types in this field? {"field1":ObjectId("53de" ...