Avoid using references when removing elements from an array in JavaScript

For a straightforward logging system, I've devised a method of storing arrays as log entries within a single array. Here's how the code functions:

var myarr = new Array();
var secondarr = new Array(4,5,6);
myarr.push(secondarr);
secondarr.length=0;
secondarr.push(5,5,5);
myarr.push(secondarr);
secondarr.length=0;

//check
for(var i = 0; i < myarr.length; i++){
    var str="";
    for(var j = 0; j < myarr[i].length; j++)
        str+=myarr[i][j]+" ";

    console.log(str);
}

To streamline the logging process, I initialize a single array myarr to store log entries. Data for logging is stored in secondarr. To avoid creating a new array each time something is logged into myarr, I attempted to reset secondarr via secondarr.length=0.

However, this action also clears out everything from

myarr</code due to references!</p>

<p>Is there a workaround to prevent the necessity of generating new arrays for each log entry? While using <code>secondarr.slice()
works, it leads to multiple arrays which I'm aiming to steer away from.

Answer №1

Make sure to update every occurrence of secondarr.length=0; with secondarr=[];. The initial command alters the array's length property that is linked to secondarr. However, the latter action reassigns secondarr to a new empty array.

Remember, a new array must be created for each logentry you wish to preserve.

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

Exploring the world of JSON and JavaScript data structures

Can someone provide some clarification please? var a = '{"item":"earth", "color":"blue", "weight":920}'; Is the data type of a a string or an array ? var b = JSON.parse(a); What is the data type of b - an object or an array ? ...

Python code used to determine the winner in a game of tic-tac-toe

Algorithm to Determine Tic Tac Toe Champion I came up with a function to identify the winner of a game of tic tac toe The input variables are provided as a list in the format shown below For example: tictactoe(["OO.","XOX","XOX"]) The code snippet ...

Retrieving the IDs of all socket connections in a Node.js Socket.IO array

I currently have a complex program utilizing socketio 0.9 where I am storing all the sockets id in arrays like so: var clients = {}; To uniquely identify and store my sockets, I assign them a serial and then set the 'socket' key with its actual ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

Troubleshooting the issue with the htmlFor attribute

I have encountered an issue with creating radio buttons and labels using JavaScript. Despite adding the 'for' attribute in the label using 'htmlFor', it does not apply to the actual DOM Element. This results in the label not selecting t ...

Retrieving JSON formatted data from PHP using jQuery

If I use a $.post method in jQuery, how can I retrieve the response from PHP? $.post("sql/customer_save.php",{ what: "edit",customer_no: $customer_no}); I want PHP to send back a response. echo json_encode(array("customer_id"=>$customer_id,"customer_ ...

Transitioning from left to right, picture smoothly scrolls into view using Way

I've explored various websites and even attempted to decipher a waypoint guide, but unfortunately, I haven't had any success. The scroll function doesn't seem to be working with the code below. (source: ) Any assistance on this matter would ...

Prevent form submission using jQuery based on ajax response, or allow it to submit otherwise

After setting up some jQuery code to handle form submission, the functionality is working well when certain conditions are met. However, I am facing a challenge in allowing the form to be submitted if the response received does not match specific criteria. ...

Unable to access Form element in Firefox browser

I'm struggling with debugging unfamiliar problems. For instance, in my HTML there's a form: <form name="myForm" > <table> <tr> <td> <input type="radio" name="myType" value="val" onclick="someF ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

Vue caution: The reference to property or method "list" during render is not defined on the instance. Ensure that this property is reactive and properly declared

I'm currently exploring the characters from the Rick & Morty series app using vue.js, and I am still learning how to use vue.js. However, I encountered the following error and would appreciate help in resolving it: Error1: [Vue warn]: Property or me ...

Configuration for secondary dependencies in Tailwind

As per the guidelines outlined in the official documentation, it is recommended to configure Tailwind to scan reusable components for class names when using them across multiple projects: If you’ve created your own set of components styled with Tailwin ...

JavaScript alerts

Can anyone recommend a quality library with beautifully animated popups? Specifically, I need a popup that allows for basic HTML fields such as text areas and more.... I am in search of a popup that will overlay on the current page, rather than opening a ...

Using jQuery to retrieve child elements and assign numerical values to them

Looking for a jQuery function that can apply different CSS attributes to children elements of a div. <div class="container"> <div class="autogenerated-div"></div> <div class="autogenerated-div"></div> <div class="aut ...

Using a pointer to access elements in a 4-dimensional array in the C programming language

Having trouble declaring a pointer in my 4d array. The declaration is as follows: int matrix[7][4][5][5] = { {/* Section 1 */ { /* 1st */ {0,0,1,0,0}, {0,0,1,0,0}, {0,0,1,0,0}, {0,0,0,0,0}, {0,0,0,1,0} }, ...

How to enable drag-and-drop functionality for an iframe?

I've successfully made a chat widget draggable using react-draggable. However, the chat widget is also consumed by an iframe created entirely with HTML. I need the iframe to be draggable as well, but react-draggable doesn't support this. Are ther ...

Include a fresh attribute within the existing JSONArray

My situation is as follows: "sections": [ { "id": XXXX, "tipology": "TIPOLOGY" }, { "id": XXXX, "tipology": "TIPOLOGY" }, {"num": 2} ], I am currently utilizing JSONArray and JSONObject. I ...

Effective techniques for unit testing in Vue.js

Here's a question that's been on my mind: when it comes to unit testing in Vue.js, there are several different packages available. Vue Test Utils Vue Jest Vue Cypress For enterprise projects, which of these options would be considered best ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...