"Unexpectedly, the original values of an array were altered by a Javascript

After creating a constructor function to generate an object, I set up an array named arr1 with initial values.

Next, I use the map function on arr1 to create a new array called arr2.

However, I noticed that the original arr1 was altered. Could this be due to the asynchronous nature of callbacks during array initialization and event loops?

On a related note, I was inspired by my previous exploration of canvas in this post when working on this code.

function point(x,y){
  return {x,y}
}

arr1 = [point(1,2), point(3,4)];
console.log(arr1, "arr1");

arr2 = arr1.map(b=>{
  b.x = b.x+2;
  b.y = b.y+2;
  return b;
})
console.log(arr1, "arr1");
console.log(arr2, "arr2");

https://i.sstatic.net/Kol2V.png

Answer №1

When working with the `map` callback, it is important to consider how you are altering properties of each object (b)...

b.x = b.x+2;
b.y = b.y+2;

If you are aiming for immutability, you might want to try something like this:

const newArr = arr.map(({x, y}) => ({
  x: x + 2,
  y: y + 2
}))

This approach creates a new array with the updated values without modifying the original array.

function createPoint(x,y){
  return {x,y}
}

const originalArr = [createPoint(1,2), createPoint(3,4)];
console.log('originalArr', originalArr);

const newArr = originalArr.map(({x, y}) => ({
  x: x + 2,
  y: y + 2
}))

console.info('originalArr', originalArr);
console.info('newArr', newArr);

Answer №2

Utilizing the map function results in the creation of a fresh array, yet this array contains references to the objects. Therefore, any modifications made to the object b in the map are essentially adjustments to the original points, not duplicates.

function point(x,y){
  return {x,y}
}

arr1 = [point(1,2), point(3,4)];

arr2 = arr1.map((b, i)=>{
  // b IS one of the objects from arr1
  console.log(`b === arr1[${i}]`, b === arr1[i])
  b.x = b.x+2;
  b.y = b.y+2;
  return b;
})

Alternatively, you can create a new point:

function point(x,y){
  return {x,y}
}

arr1 = [point(1,2), point(3,4)];
arr2 = arr1.map(({x, y}) => point(x + 2, y + 2))

console.log(arr1, "arr1")
console.log(arr2, "arr2")

Answer №3

The explanation for the behavior you are observing is that .map() creates shallow copies of the elements in a new array.

This particular line modifies the values of x and y in each element of the original array.

arr2 = arr1.map(b=>{
  b.x = b.x+2;
  b.y = b.y+2;
  return b;
})

It is advisable to only return new values for x and y without altering the original array element, like so:

arr2 = arr1.map(b => {
  return {
    x: b.x + 2,
    y: b.y + 2
  };
})

You can use the code snippet below to generate a new array with updated x and y values without changing the original array elements.

function point(x, y) {
  return { x, y }
}

arr1 = [point(1, 2), point(3, 4)];
console.log(arr1, "arr1");

arr2 = arr1.map(b => {
  return {
    x: b.x + 2,
    y: b.y + 2
  };
})
console.log(arr1, "arr1");
console.log(arr2, "arr2");

Answer №4

One aspect that has been highlighted is the issue related to reassigning values to your arr while using map. However, it is important to note the side effect you witnessed with the initial console log on arr1 being updated as well. This behavior can be seen as a limitation, depending on the perspective.

function createPoint(x,y){
  return {x,y}
}

arr1 = [createPoint(1,2), createPoint(3,4)];
console.log("arr1 closed", arr1);
console.log("arr1 opened:", arr1[0], arr1[1]);

arr1[0] = {x: 15, y: 42};
console.log("arr1 closed", arr1);
console.log("arr1 opened:", arr1[0], arr1[1]);

jsFiddle

Take note of how the "opened" arrays display the values at the time the console log was executed. However, when expanding the first console log with the nested array, it shows the updated values.

This side effect cannot be observed by running the code as a snippet. It needs to be executed in a browser for the console to show the output.

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

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Steps to resolve the issue: The current experimental syntax 'classProperties' is not supported

I encountered an issue where the experimental syntax 'classProperties' is not supported when trying to run my react js application. My goal is to increment the value inside a <span> when a ` button is clicked. Below is the excerpt of my c ...

When utilizing a clone in a Draggable and Droppable scenario, the data/attribute is obtained from the

Currently, I am struggling with retrieving data/attributes from the original item when using jQueryUI draggable/droppable to move rows between tables. I have set helper: 'clone' but am finding it difficult to access any data from the dragged item ...

Running JavaScript code for the iframe

Question about Manipulating Content in an iFrame: Invoking javascript in iframe from parent page I am attempting to load a HTML page with an iFramed website and then manipulate the content by removing an element, referred to as '#test'. < ...

Updating state based on input from a different component

I am attempting to modify the state of the page index in index.js from the Pagination component, Here is my index.js code: import useSWR from 'swr'; import { useState } from 'react'; const Index = ({ data }) => { const ini ...

What is the process of saving an empty array as a property of a nested object in Mongoose?

Here is a snippet of the code I am working with: const newLesson = new Lesson({ classroomId: req.params.classroomId, name: req.body.name, startDate: startDate1, endDate: endDate1, ...

Tips for positioning a div element within the body of a webpage to maintain a predetermined height and width

Currently, I am developing a single-page application using AngularJS. I have specific routes in mind where I want to introduce new HTML templates. To accomplish this, I have created a container labeled with the ID #main positioned between two navbars (he ...

What is the significance of the exclamation point before and after in JavaScript?

Currently collaborating on a project and attempting to decipher the significance of the exclamation marks both before and after. import ICHING from '!json!constants/iching_deoxy.json'; ...

Dispatching information to a designated Google Analytics tracking code

Within our website, we have a unique dimension that is configured on Google Analytics and utilized when sending the page view event: gtag('config', 'UA-TrackingCode', { 'custom_map': { 'dimension1': &apo ...

Display a DIV next to the mouse cursor when a span is hovered over

Is there a way to make a DIV element appear at the mouse cursor when a user hovers over a SPAN or another DIV? I attempted to create a function for this purpose, but unfortunately, it does not seem to be working properly even though jQuery is correctly lo ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

`Is there a way to modify the zAxis of a Paper component in Material-UI?`

Hello, I am curious about how to change the z-axis of a paper from MUI. https://i.sstatic.net/iKXLG.jpg The issue I'm facing is that the carousel is overlapping my menu and I need the menu to be on top of everything. Here is how I have it structure ...

"Trying to access the Reducer in a container results in an undefined value

I recently tried adding a new Container to my React App, connected it with Redux, and wanted to test if everything was functioning properly. Unfortunately, when I try to access the reducer using this.props.selection, it returns as undefined. This is puzzli ...

Accessing Facebook through the React create app login

I recently developed a React Webapp using the create-react-app module. My current challenge involves integrating Facebook login, but I'm encountering some obstacles. I am unsure about where to incorporate the Facebook JavaScript SDK asynchronously to ...

Is it possible for a dash in a GET variable name to cause issues with req.query in NodeJS Express?

I am currently developing a GET endpoint in Node.js using Express to handle the following variable: ?message-timestamp=2012-08-19+20%3A38%3A23 However, I am facing difficulty accessing it through req.query. Whenever I try to access req.query.message-time ...

Material-UI: The call stack has exceeded the maximum range, causing an Uncaught RangeError

I am currently utilizing the Dialog and Select components offered by Material-UI in conjunction with React. Here is a quick example: import React from 'react'; import { Dialog, MenuItem, Select } from '@material-ui/core'; class Examp ...

What is the best way to animate changes to a background image using jQuery?

Exploring the possibilities of creating a unique visual effect reminiscent of a pulsing heartbeat for a button. I'm under the impression that achieving this is beyond the scope of CSS. Can anyone shed light on how to implement an animated background ...

Updating a function in jQuery UI after dynamically loading content through AJAX

I've been on a quest for days now, searching high and low for an answer to my dilemma. While I've managed to solve most of the issues that arose after adding AJAX calls to my code, there's one piece that still eludes me. Just to provide som ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...