Adding elements to an array in jQuery by pushing them

I have been attempting to populate an array with objects, but for some reason, the array is not filling correctly. The last value seems to be set in all positions of the array. Below is the code snippet I am using:

var matrixprice = 5;
var qualifiedDate = '2019-10-01';

var today = new Date();
var qDate = new Date(qualifiedDate);
var nextDay = qDate;
var myObject = new Object();

var myArray = [];

var dailybonus = matrixprice * 0.03;

var full_bonus = matrixprice * 2;

var i = 0;

while (i <= full_bonus) {

  nextDay.setDate(nextDay.getDate() + 1);
  i += dailybonus;

  myObject.title = '$' + i;
  myObject.start = nextDay;

  myArray.push(myObject);
}


var myString = JSON.stringify(myArray);

console.log(myString);

The issue I'm facing is that the resulting array contains only one value repeated across all positions like this:

[{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},           {"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"}]

Your help is greatly appreciated!

Answer №1

Revise your while loop to add a new element:

while(i <= full_bonus){
    nextDay.setDate(nextDay.getDate()+1); 
    i += dailybonus;

    myArray.push({title: '$'+i, start: new Date(nextDay)});
}

Check out the complete, functioning code snippet below:

var matrixprice = 5;
var qualifiedDate = '2019-10-01';

var today = new Date();
var qDate = new Date(qualifiedDate);
var nextDay = qDate;

var myArray = [];
var dailybonus = matrixprice * 0.03;
var full_bonus = matrixprice * 2;

var i = 0;

while(i <= full_bonus){
    nextDay.setDate(nextDay.getDate()+1); 
    i += dailybonus;

    myArray.push({title: '$'+i, start: new Date(nextDay)});
}

var myString = JSON.stringify(myArray);

console.log(myString);

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

For all URLs, redirect from HTTP to HTTPS unless the request is coming

I recently transitioned my node.js app to use https. To achieve this, I configured https through an nginx reverse proxy. However, I encountered a problem where, when I type in example.com, it does not automatically redirect to https://example.com. In an at ...

Is it possible to use AngularJS promises without callbacks?

Typically, when I want to retrieve data asynchronously, I would use the following approach: var promise = $http.get('/api/v1/movies/avengers'); promise.then( function(payload) { $scope.movieContent = payload; }); This scenario is quite ...

Dividing and conquering to find the minimum sum of consecutive values

When tasked with finding the minimum sum of two consecutive values in an array of random integers using divide and conquer, my IQ seems to be working against me. What's not working here? N = [1,...,n] To solve this problem, I wrote a function minSum ...

Having trouble replicating the progressive response from the server in node.js

Hey there, I recently dipped my toes into the world of node.js and decided to give it a shot. Following Ryan Dahl's tutorial (http://www.youtube.com/watch?v=jo_B4LTHi3I) as my starting point, I reached a section around 0:17:00 where he explains how s ...

AngularJS offers a variety of 'select all' checkboxes tailored for specific lists of checkboxes

Within my webpage, I have three different sets of checkboxes. Each set includes a "select all" checkbox. Instead of repeating code lines, I am implementing a single function with a parameter to select specific checkboxes within each set. $scope.sele ...

Loading webpage with Ajax and verifying status code

I'm having an issue with a code that is meant to check if a page has loaded and then alert me with a status. However, the code doesn't seem to be working properly. I would really appreciate it if someone could take a look at it and point out wher ...

What is the best way to merge values in an array based on their keys?

Here is a sample of the data I have: data = [ [ {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]}, {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]} ], [ {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]}, {" ...

What is the best way to activate a Rails controller action in response to a JavaScript event?

I'm in the process of developing a Rails application and I have a requirement to trigger an Update action from one of my controllers based on a JavaScript event. Here's what my controller action looks like currently: def update @subscrip ...

Activate the prompt for saving a static file on Flash

Is there a way to prompt a save dialog for a static file in Flash? The file could be local or remote. Specifically, I am looking to do this with a static image. Being new to AS and SO, it's surprising to see the range of complex solutions for what se ...

Obtain the height and width of the original images from the href and assign them to your attributes using jQuery

Hey there pals, I'm currently on a mission to fetch the dimensions (height and width) of an image from a hyperlink and then insert those values into its attribute. This task has got me going bonkers! Here's my snippet: <figure> <a ...

Is there a way to determine if a collapsed navbar is currently open?

My Bootstrap 4 navbar collapses on mobile, and I'm looking to detect when it opens and closes. Is there a way to achieve this? Thank you! ...

How can Reactjs display a preview of an image and retrieve the image file?

Here is a code snippet I wrote for previewing images before upload. However, I have encountered an issue where I can either preview the image or get the file for upload, but not both at the same time. If I change return URL.createObjectURL(file); to retu ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

How can you use Require.context in Webpack to import all .js files from a directory except those ending in `_test.js`?

My objective was to develop a script that accomplishes the following tasks: Import all JS files from a directory excluding those ending in _test.js Set up a module.exports containing an array of module names extracted from those imported files. Initiall ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

What is the best way to implement Breadcrum in AngularJS?

I'm looking to integrate breadcrumbs into my application using AngularJS. I've already set up the router and header file, but I'm unsure of how to proceed with implementing breadcrumbs in AngularJS. INDEX <div class="container mainI ...

Improving Load Times in Next.js

I've made an interesting observation: when I execute the npm run dev command to start the code, the initial page load takes much longer compared to subsequent page refreshes. Upon inspecting the network tab in Chrome DevTools, I discovered that the f ...

Using Query strings in JavaScript: A Quick Guide

I recently completed a calculator project with only two pages. However, I am struggling to figure out how to pass input field values from one page to another. Despite trying multiple methods, nothing seems to be working. Does anyone know how to successful ...

Express serving Node JS HTML pages

I am currently developing a multiplayer game where a server connects two clients to battle against each other. Everything seems to be working smoothly so far. However, I now have the task of integrating a welcoming page where players can input their userna ...

Different ways to save data fetched from a fetch request

I'm fairly new to React and could use some assistance. I am trying to retrieve data from a movie database based on a search term. I have a method called getMovies where I utilize fetch to grab the data. The information is located in data.Search, but I ...