The function array.push() is not achieving the intended outcome that I had in mind

Currently facing a rather frustrating issue. I'm attempting to utilize D3.js for dynamically plotting data (specifically, scores of individuals).

  1. Retrieving record data from a firebase database whenever changes occur - this is represented by an object containing static score data.
  2. Adding a time key/value pair to the record.
  3. Preparing the data for D3 by creating an array named 'data' where the record is added every second using data.push(record).
  4. While successfully outputting the record object to the console as intended, encountering issues with the time value displaying in a loop - it's showing the current time value for all elements, including past ones.

It has been approximately 3 hours since I got stuck on this problem.

If anyone can provide assistance, it would be greatly appreciated. Thank you.

var data = [];
record = {Fanny: 40, Joe: 20};
var time = 0;

record["time"] = time;

console.log(record);

myTimer = setInterval(function () {

    time = time + 1;

    record.time = time; 

    console.log(record);

    data.push(record);

    for (i = 0; i < data.length; i++) { 
          console.log(data[i].time)
    }
},1000);

Answer №1

It is essential to create a fresh entry for each loop cycle.

At the moment, you are only using one identical (albeit duplicated in the array) entry and continuously modifying it.

data.push({ Fanny: 40, Joe: 20, time: time });

Answer №2

If you're faced with a referencing problem, it could mean that:

Let's say you have an object 'a'

a.name = 'toto';
var b = a;
b.name = 'titi';

console.log(a.name) // this will output 'titi'

To work around this issue, one not-so-pretty solution is to:

var b = JSON.parse(JSON.stringify(a));

which will break the referencing.

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

Problem with Bootstrap loading state when certain input fields are required

Just starting out with Bootstrap 3 and looking to integrate the loading state button function into my form. I've set up an input field with the required option as shown below. <form> <input class="input" name="title" type="text" required / ...

Is it possible to pass arguments to setTimeout function?

At the current moment, my code looks like this: function showGrowl(lastNumber) { var num = lastNumber; //keep generating a random number untill it is not the same as the lastNumber used while((num = Math.ceil(Math.random() * 3)) == lastNumber); ...

Next.js 13's App Router experiences a 404 error when refreshing due to the parallel route modal configuration

I am attempting to create a modal using parallel routes in Next.js version 13.4. Everything functions properly when I am on the homepage (/) and open the modal by navigating to /login. However, if I refresh the /login page, instead of displaying the home ...

Ensure Owl Carousel 2 is set up to disable drag functionality on desktop devices while enabling click through functionality

I am currently working with Owl Carousel 2 and I want to create a unique interaction for desktop while keeping the default touch swipe interaction for mobile devices. I have managed to disable mouseDrag using the JS code below, but now I am looking to add ...

Ensuring session data is updated when saving a mongoose model

I am facing a challenge with updating express session data in the mongoose save callback. Is there a way to access and modify the session data from within line 4 of the code? app.get('/', function(req, res){ var newModel = new Model(somedata); ...

When trying to set the state in the OnMouseOver event, an error is thrown: TypeError - React is

Despite encountering numerous posts discussing this issue, I am struggling to resolve it in my particular scenario. I have a collection of items that I am attempting to apply color changes to (the div's) when they are hovered over. The coloring only ...

Executing 'npm run bundle' with Webpack results in an ERR! with code ELIFECYCLE

As someone new to using Webpack with AngularJS apps, I am eager to learn but facing some challenges. Following the guide by Ken Howard has been helpful, but I encounter an error when attempting to run the bundle. Article by Ken Howard that I've been ...

Modify CSS using JavaScript at a specific screen size

Currently, I am in the process of designing a responsive navigation system which involves implementing a button that dynamically changes the styling of the div #navigation using Javascript. The aim is to toggle between display: none; and display: block; ba ...

Make changes to the HTML file by directly using Jquery or JavaScript

Allow me to elaborate on my current objective. I have an HTML file that requires direct content updates. Specifically, I am working with elements sharing the 'id=test'. My goal is to dynamically update all elements with unique IDs such as ' ...

If the element is checked and equal to a specific value, take action

I am trying to hide one of the 3 radio buttons on my page. Although they all have the same class, each button has a different value. I attempted to write code to achieve this, but unfortunately, it is hiding all radio buttons instead of just one. Could s ...

Mastering the art of utilizing sequelize and promises effectively

I'm currently learning how to create apps using expressJS and Sequelize. I could really use some help as I'm more accustomed to sequential programming. My project involves two models: Todo (id, title) and TodoItem (id, content, complete, todoId). ...

There was an unexpected token syntax error while trying to assign the database URL from the environment variable "REACT_APP

I am facing an issue with setting an environment variable in my mongo.js file. Here is the code snippet where I have set the ENV variable: const mongo = require('mongodb').MongoClient; const assert = require('assert'); const ObjectId = ...

Keep the Bootstrap modal open while the JavaScript validation is running, and redirect the form action if the validation is successful

When trying to execute the submit event from a form, my code is supposed to keep the modal open if validation fails. However, for some reason, this functionality is not working as expected. var myForm = document.updteform; var condition = true; if ...

Attempting to insert the symbol "$gt" into a query for a search. {[CastError: Unable to convert value "[object Object]" to date at path "createdAt"]}

In the following code snippet: Reviews.find({createdAt : {"$lt" : app.locals.lastDate}}), I am trying to dynamically change the $lt to $gt. app.post("/scroll", function(req, res){ console.log("req.body...", req.body); var sortCreate = req.body.old ...

Tips for verifying that input is provided in a text field when the checkbox is marked

Can someone help me with validating a form where the user must enter data in a text field if they check a checkbox? I have JavaScript code for checkbox validation, but need assistance with text field validation. Thank you! $(document).ready(function () ...

When dalekjs attempted to follow a hyperlink with text in it, the link failed to function properly

My goal is to retrieve an element from a list by clicking on a link containing specific text. Here is the HTML code snippet: <table> <td> <tr><a href='...'>I need help</a></tr> <tr><a href=&a ...

I'm curious about how I can apply @media queries given that certain phones possess higher resolution than computers

There seems to be a common recommendation to utilize @media queries for adjusting CSS based on whether the user is on mobile or not. However, I'm a bit confused because my phone has a width of 1440p while my computer has 1920p. Should I consider apply ...

How can we ensure that the Material-UI <Select> component is as wide as the widest <MenuItem>?

I am attempting to adjust a Mui Select field so that it is the same width as its largest MenuItem. Despite trying to utilize the autoWidth prop on the Select component, I have not been able to achieve the desired result. To better illustrate the issue, I h ...

PHP code to display all the days between a specified date and the last day of the month

I definitely don't want to send back the DATE in the format Y-m-d. My goal is to display all the days up to the end of the month starting from a specific day regardless of the month or year. I attempted both [$array as $i] and [$array as $key], but ...

I'm having trouble getting my application to output to the console. What could be the issue?

In my cr-route.js file, I have a function that ensures the user is authenticated before displaying their name. module.exports = function (app, passport) { // ===================================== // HOME PAGE (with login links) ======== // == ...