Creating an array in Javascript and populating it with dynamically generated values

I am currently iterating through 3 arrays, searching for 'actionTimings' in each array and summing up the values of actionTimings (which are all numbers). How can I store these 3 values in a new array? This is what I have tried so far...

$.each(dinnerComponents, function(intIndex, component) {
    totalCookTime = 0;
    for ( var i = 0; i < component.actionTimings.length; i++ ) {
        totalCookTime += component.actionTimings[i];
    }
});

I attempted to do this:

totalCookTime = new Array(totalCookTime);

However, this array contains sets of commas. It seems like the number of commas equals totalCookTime-1. Is this due to the values being comma separated within the array? My understanding of arrays is somewhat limited, unfortunately.

Thank you for any assistance.

Answer №1

To calculate sub-totals for each 'dinerComponent', you can utilize the Array push method:

var totalAmounts = [];  // storing the sub-totals for each 'dinerComponent'
$.each(dinnerItems, function(index, item) {
  var sumQuantity = 0;
  for ( var j = 0; j < item.quantities.length; j++ ) {
    sumQuantity += +item.quantities[j]; // using unary plus to convert to Number
  }
  totalAmounts.push(sumQuantity);
});

Answer №2

The main issue you are encountering is that using new Array(n) creates an array with n "slots".

One solution is to utilize jQuery's "map" function, which can convert one array into another:

var totalCookTime = $(dinnerComponents).map(function (component) {
    var cookTime = 0;
    $(component.actionTimings).each(function (index,timing) {
        cookTime += timing;
    })
    return cookTime;
}).get();

(The final .get() method returns a true array rather than a jQuery object pretending to be an array.)

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

Essential Understanding of HTML Query Strings Required

As a newcomer to the world of web design, I have taken on what seems like a challenging task for me: creating a webpage that can send a query string to the German Railway website (bahn.de) with the parameters I input. My question now is whether there is a ...

Output a single value from an array

After fetching an array of product IDs and names from the product table, I attempted to display a single product name but ended up only seeing the first letter of the name. Below is the segment of code that I utilized. Any insights or guidance would be g ...

How should the array.sort(a, b) method be properly used after the recent updates in node.js version 11.0.0 and above?

After successfully running code and passing tests on node 10, we encountered issues when upgrading to node 11. The code, which maps over an array of objects and alters properties, now fails unit tests after the upgrade. The code should sort based on a stri ...

How can one transfer information from a client to a server and complete a form using JavaScript?

Can the information be transferred from a client to the server using just JS, then fill out a form on the server, and finally redirect the client to view a pre-filled form? I am considering utilizing AJAX to send a JSON object, but unsure if it will be s ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

Error message: "When using selenium-webdriver in JavaScript, the findElement method for <a> tags cannot be used as a function."&

Seeking the website URL for brand information from this website, I attempted to retrieve it using JavaScript in the console: document.getElementById('phone_number').getElementsByTagName('a')[1].getAttribute('href') However, ...

Combine all possible pairings of elements from two distinct arrays

Is there a way to combine the elements of two arrays and return them in a new array? Let's say we have these two arrays: const whoArr = ["my", "your"]; const credentialArr = ["name", "age", "gender" ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

Change the destination of an iFrame upon user click

Is it possible to redirect an iFrame to a different HTML page when clicked by the user? I have an iFrame that is essentially an HTML page. When I click on the iFrame, I want it to take me to another HTML page. This is my code: h1 { ...

Using ngTable within an AngularJS application

While working on my angularjs application, I encountered an issue with ngtable during the grunt build process. It seems that the references are missing, resulting in the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module pa ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

Is there a way to verify if the $compile process has finished?

I am currently developing a function that can dynamically create an email template from an HTML template and some provided data. To accomplish this, I am utilizing Angular's $compile function. However, I have encountered a challenge that I seem unabl ...

What is the best way to resize an array to a different length while preserving its close values in R programming?

I have two arrays with varying lengths value <- c(1,1,1,4,4,4,1,1,1) time <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) How can I adjust the length of the value array to match the length of the time array while preserving its approximate values? The a ...

Retrieving variables using closures in Node.js

I have been developing thesis software that involves retrieving variables within closures. Below is the code snippet written in node.js: var kepala = express.basicAuth(authentikasi); // authentication for login function authentikasi(user, pass, callback ...

An issue arose in Leaflet where drawing on the map became impossible after making an update to a marker's position

I have been working with Leaflet, Leaflet-draw, and Cordova Geolocation. Initially, when the map is loaded in globe view, drawing works perfectly. However, when the locate function is called to update the map center and marker position, drawing becomes imp ...

Troubleshooting AngularJS form submission with missing data

Is there a way to modify AngularJS to save form data into a database using PHP as the backend? Below is the HTML form code: <form ng-submit="newContactSubmit()"> <label>FirstName<input type="text" name="contact_firstname" required n ...

How to decode JSON data into a JavaScript array and retrieve specific values using index positioning

Upon receiving a json response via ajax, the code looks like this: echo json_encode($data); The corresponding ajax code is shown below: $.ajax({ url:"PaymentSlip/check", data:{val:val}, type: 'POST', succe ...

How to use jQuery to dynamically assign a class to an li element

I'm attempting to use jQuery to add the 'block' class to specific li elements, but for some reason the class isn't being applied. The goal of the program is to display time slots and disable certain ones if they are blocked. Here's ...

python implementing a function with sleep to continuously loop without halting the entire program

Many individuals suggest using threading, but how can the remainder of the program continue running while that specific thread sleeps, then restarts, and falls asleep again? I attempted traditional threading with a while loop, but it was not successful for ...

The updates made to a form selection using Ajax do not reflect in jQuery's .serialize or .val functions

When using the .load jQuery function to retrieve a form and place it in the document body, I encounter an issue. After loading the form, I manually change the select value and attempt to save the form using an ajax .post request. However, when trying to ...