JavaScript forEach: alter items

I am facing an issue with using the forEach method on an array. Despite it being a mutator, it is not mutating the values in the original array as expected. Can anyone help me figure out what could be causing this problem?

let array = [1, 2, 3, 4]; //declaring a simple array

array.forEach((ele) => ele * 2); //using forEach to double each element in "array"

console.log(array); //expecting [1, 4, 6, 8] but getting [1, 2, 3, 4] instead

Any insights on why this is happening?

Answer №1

Contrary to popular belief, forEach does not actually alter the original array.

To achieve the desired outcome, you can specify a second parameter as index and then update the values of the original array accordingly.

let numbers = [1, 2, 3, 4];
numbers.forEach((element, index) => numbers[index] = element * 2);

console.log(numbers);

For more information on using forEach, refer to the documentation.

Answer №2

Array#forEach method allows you to utilize the second and third optional parameters for accessing and modifying each element:

index [Optional]: Specifies the index of an element in the array.

array [Optional]: Refers to the array on which forEach() is invoked.

const array = [1, 2, 3, 4];

array.forEach((_, index, arr) => arr[index] *= 2);

console.log(array);

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

Tips for stopping execution in Discord.js if the user no longer exists?

I'm currently working on a discord bot and encountered a minor issue. I am using "messageReactionRemove" and "messageReactionAdd" to manage certain roles by removing or adding them, but the problem arises when a user leaves the server. When this happe ...

Show PDF within the browser using ajax technology

I've come across this question multiple times in various forms, but I still can't seem to find a satisfactory answer. When using the mpdf library to generate PDFs, I send some hidden field data to a PHP script via ajax. Below are snippets of the ...

Alter attribute with an impact

I am looking for a solution to switch the image source using attr, while also incorporating a fade effect in the process. I have attempted to implement one of the suggestions from another post, but it is not producing the desired outcome. Current Appearan ...

Is it possible to run a local file on a localhost server in Sublime Text 3 with the help of the SideBar

I am attempting to host my index.html file on a localhost server in order to utilize an angular routing directive. Despite following the steps, I am encountering issues. //sidebarenchancements.json { "file:///C:/Users/Jdog/Desktop/projects/Calibre/soci ...

Utilizing Vuejs and ElementUi to enhance slot filtering capabilities

I am facing an issue with a table where one of the columns is using slot-scope, and I am struggling to include that column data into the filters option. Code Component filter input <el-input v-model="filters[0].value" placeholder="Type t ...

Set the radio button in Angular to be checked on the first option

I recently created a dynamic form with data from an API, including an ng-repeat to generate multiple radio buttons. Everything is working well, but I'm struggling to set the first radio button as checked by default. Any suggestions or solutions would ...

Steps for adding a delete icon to a text input field and enabling the functionality to delete text

In the code snippet below, I am creating a text input field: <input type="text" class="signup-input text-value" name="" placeholder="e.g. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d48554c405d41486d">[email pro ...

What are the steps to incorporating an Image in a React Native application?

My Image is not showing up when I try to render it using image uri, and I'm not sure why. Here is the code snippet I'm using in a React Native project. import React from 'react'; import styled from 'styled-components/native'; ...

Retrieve a JavaScript object based on a specific value

Looking at my object : TeamMember = { 0 : {"ID": 100, "Name": "MNO", "Role": 2}, 1 : {"ID": 101, "Name": "PQR", "Role": 3}, 2 : {"ID": 103, "Name": "STU", "Role": 3} } I am trying to retrieve TeamMember[1] : {"ID": 101, "Name": "PQR", "Role": 3} a ...

When a new ajax function is added, the original Ajax code stops functioning

I've been working on getting the code below to function properly. It seems that when I test the code, two validation functions are working correctly. However, when I include the validateUsername() function along with the if statement in the code, ever ...

Automatically focus on input when scrolling reaches a specific element using jQuery

I have been utilizing a jQuery plugin called Waypoints to handle scroll actions. My goal is to focus on the first input element of a section that is currently visible on the screen and then shift the focus to the input of the next respective sections as t ...

pm2 initiates two identical processes using distinct versions

I am currently using pm2 version 4.2.3 Upon executing the command: pm2 start node launchers/engine_launcher.js --name "engine", it initiates the following processes: id │ name │ namespace │ version │ mode │ pid - ...

The issue with IE-9 is that it is mistakenly picking up the placeholder value as

My HTML code looks like this: <input id="SLOCriteriaOtherText" name="SLOCriteriaOtherText" style="width: 100%;" type="text" data-role="autocomplete" placeholder="Enter name for 'other' metric..." class="k-input" autocomplete="off" role="textb ...

Attempting to display an image based on the outcome of a function that was executed earlier

As a beginner in the world of JavaScript, I kindly ask for your patience and detailed explanations in helping me understand the concepts. My current project involves creating a button that randomly selects a name from a list and displays it along with an ...

What is the reason behind requiring a variable declared within a method to be marked as final when being utilized in an inner class defined in the same method?

I hope you don't mind me bringing this up again, as I couldn't quite understand the reason behind it. Can someone please shed some light on this issue for me? For example: public class File { public static void main(String[] main) { ...

` Why isn't Glide.js functioning correctly when incorporated into a Bootstrap 4 modal component?`

I'm currently utilizing Glide.js and a Bootstrap 4 modal on our team page to showcase the biography of the selected team member. This functionality is achieved by extracting the attribute of the clicked team member and using it as the startAt: index f ...

The functionality to organize items appears to be malfunctioning. (Javascript)

I want to add a price sorting feature that allows users to sort by either 'high to low' or 'low to high' using a drop-down menu. The products I want to sort are the w3-containers, each representing a different product. However, nothin ...

What could be the reason for the lack of rendering in this imported React component using System.import?

I've been experimenting with dynamic code splitting using webpack 2 and react. As part of my testing, I decided to create a component that fetches code asynchronously: import React, { Component } from 'react' export class Async extends Com ...

tips on retrieving the Vue element using a method in Vue.js

How can I dynamically add an element to the array by clicking a button in vue.js? Is it possible to call the method aggiungiViaggio on click, and how do I determine which viaggio I am currently in? Below is an example of the HTML: <div class=" ...

How to retrieve a randomly selected subset from a MongoDB database using Express

Recently, I have been diving into the world of coding and decided to create a trivia game using Mongo, Express, and NodeJS. The game pulls random trivia questions from a database, allows users to input answers, and verifies if they are correct. However, I ...