jQuery has revolutionized web development by introducing a new array

Having a problem with managing a jQuery array.

My goal is to create two distinct arrays.

var main_array = []

function initialize_arrays(){

   main_array[0] = {id: 1, status: true, number: 10};
   main_array[1] = {id: 1, status: true, number: 16};
   main_array[2] = {id: 1, status: true, number: 20};

}

function adjust_number(array, index, new_number){

   array[index].number = new_number

}

initialize_arrays()

new_array = adjust_number(main_array, 0, 20); 

console.log(main_array)

The issue I'm facing is that when I try to modify an element in the $main_array and create a new array, the original main_array also gets changed.

I specifically want to avoid changing the numbers in the main_array.

I'm having difficulty figuring out what might be going wrong here.

Answer №1

When dealing with arrays in JavaScript, it's important to remember that they are objects. This means that when you pass an array as a parameter to a function, you are actually passing a reference to the memory location of the array, not a copy of the array itself. Therefore, any modifications made to the array within the function will affect the original array.

Furthermore, if your array contains objects, those objects are also passed by reference. In order to work with copies of these objects instead, you can use the Object.assign() method.

One other thing to note is the convention of prefixing identifiers with a dollar sign to indicate that they hold references to JQuery wrapped set objects. If you're not using JQuery in your code, it's recommended to remove this prefix.

var main_array = [];  // <-- This is where the main array will go
var newArray =   [];  // <-- This will be where the copied array goes

function create_array(){

   main_array[0] = {id: 1, status: true, number: 10};
   main_array[1] = {id: 1, status: true, number: 16};
   main_array[2] = {id: 1, status: true, number: 20};
   
   return main_array;
}

function change(array, key, number){
   // Loop thorugh the original array:
   main_array.forEach(function(obj){
    // Make a copy of the objects in the array and put them in the new array
    newArray.push(Object.assign({}, obj));
   });
   newArray[key].number = number
}

main_array = create_array();

change(main_array, 0, 20); 

console.log(main_array, newArray)

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

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

Autocomplete Dropdown failing to select default value when defaultValue option is set

stateNPAValue[formData.state.vale] = 0: "All",1: "959", 2: "203",3: "860", 4: "475" // API response for NPA data const [selectedNamesState, setSelectedNamesState] = useState([]); const transformedNpaData ...

Optimizing Firebase rendering with useEffect

I'm facing an issue where the console for currentUser keeps rendering constantly. I have added the necessary dependencies for currentUser and even included cleanup, but it still re-renders. const [currentUser, setcurrentUser] = useState({}); con ...

Specifying the data type of the input being passed into a .css() function within a jQuery ID selector

Currently, I am facing an issue where I need to position an element below a fixed toolbar. The amount of top-padding required for this positioning varies based on the viewport width. To address this, I have created a formula that calculates the percentage ...

An array of NSObjects and boolean values

Is it possible for an NSArray to store an array of boolean values? The code snippet below demonstrates this: BOOL isTrue = NO; NSMutableArray *boolArray = [[NSMutableArray alloc] init]; [boolArray addObject:[NSNumber numberWithBool:isTrue]]; NSLog(@"Th ...

Discover how to implement custom data filtering in an Angular controller

Help needed: How can I remove decimals, add $ symbol in an Angular controller? Any ideas? $scope.data = [{ "key": " Logo", "color": "#004400", "values": [ [0, parseInt($scope.myappslogo)] ] }, { "k ...

JavaScript click event to open a URL in a new window

I am trying to create a hyperlink with text using HTML, and I want it so that when the user clicks on it, it redirects to a specific URL. I am new to JavaScript! Here is my code: <a class="dt-button add_new_table_entry DTTT_button DTTT_button_new" tab ...

How do I deactivate dragControls in THREE.JS after enabling them for a group of elements?

My function currently activates dragControls when the "m" key is pressed, but for some reason, it doesn't deactivate when the key is released. How can I go about disabling the dragControls? I attempted to encapsulate the dragControls activation based ...

Convert a single array into an array of objects, with keys derived from a JSON response in JavaScript

After making an API call, I am capturing a json response. My goal is to extract the keys and generate an array of objects dynamically, regardless of the number of keys in the response. To get the keys, I have implemented the following function: const json ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

Encountering an issue when attempting to import a non-source module from a node library while running a Typescript script

I have a script that takes input and utilizes the three.js library to apply geometric transformations to the data. I execute this script using ts-node pipeline.ts. Here is the structure of my project: ├── package-lock.json ├── package.json ├ ...

Having trouble getting angular-masonry to function properly as it keeps throwing an error saying it does not recognize the method 'imagesLoaded'

I am currently attempting to integrate the angular-masonry plugin by passy with an infinite scroll directive, but I'm encountering some issues. I have set up a plunk for this here. The console is displaying an error message that reads "TypeError: Obje ...

Navigating and organizing with React Native: TabBarIOS and Navigation

I have a basic app that consists of 3 tabs. The tabs are set using TabBarIOS in the index.ios file. I am not utilizing Navigator or NavigatorIOS. In each TabBarItem, I directly include the component name within tags. Here is an example: return( &l ...

The concept of tweening camera.lookat in Three.js

Struggling to smoothly tween the camera.lookAt method in Three.js using Tween.js. The current implementation rotates the camera directly to the object's position. Here is the code snippet that sort of works: selectedHotspot = object; var tw ...

What is the process for creating a new subdocument if it doesn't already exist, and then appending another subdocument below it?

On my mongoose schema, I have a user schema with a property named lastExams defined as follows: lastExams: [{ lecture: { type: String, required: true }, exams: [{ examID: {type: [mongoose.Schema.Types.Obj ...

Is it possible to generate output from a string dust template without the need for prior compilation?

Can dustjs be used to dynamically render templates without compiling them first? > > var dust = require('dustjs-linkedin'); > > dust.stringRender("Hello {name}, how are you?", { name: "Joe" }, function(err, res) { > console. ...

Using jQuery to dynamically pass variables to an HTML document

In my JavaScript file, I have the value 'testValue' stored. The code snippet below retrieves this value using a REST service and displays it in an input box: $('#testValue').val(RestServices.getValueCovid(response, 'TESTVALUE' ...

The functionality of Google Maps fails to operate within an Angular directive

Trying to implement the GoogleMapsAPI but facing issues with displaying the map in the directory template. Check out the following markup and code snippet: <gmap-locator></gmap-locator> . app.directive('gmapLocator', function () { ...

Populate an array of uint16_t with data from uint64_t in C programming

I am struggling to figure out how to store a data of uint64_t size into 4 uint16_t positions in an array without using any loops... Below is a snippet of my code: static int send(uint16_t addr, const void *data) { uint16_t frame[7]; /* My goal is ...

Creating dynamic 2-dimensional math matrices using malloc

While a similar question has been posed before, such as in this post: Malloc a 2D array in C I am interested in determining whether it is more advantageous to utilize a traditional 2D array structure (employing pointers of pointers) or if opting for a fl ...