Find the sum of object prototype differences in JavaScript

Struggling with a JavaScript challenge - I need help creating a JavaScript script where the user inputs the month and the amount of rain for that month, and the program generates a table showing the total rain for each repeated month. For example, if January is entered three times, the table should display the sum of rainfall for those three entries.

I've attempted to write the code but it keeps looping twice for repeated months and I can't figure out how to stop it after calculating the total rainfall for the repeats. Here's the current code:

var proceed = true;

function Month(month, rain) {
  this.month = month;
  this.rain = rain;
}

data = [];

months = ["January", "February"];

while (proceed) {
  var month = prompt("Enter the month", "");
  var rain = parseInt(prompt("Enter the millimeters of rain for the month", ""));

  new Month(month, rain);
  data.push(new Month(month, rain));
  proceed = confirm("Do you want to continue?");
}


for (var j = 0; j < data.length; j++) {
  if (data[j].month == months[0]) {
    var initialValue = 0;
    var sum = data.reduce(function(accumulator, currentValue) {
      return accumulator + currentValue.rain;
    }, initialValue)
    
    document.write("<table>");
    document.write("<tr>");
    document.write("<td>" + data[j].month + "</td>");
    document.write("<td>" + sum + "</td>");
    document.write("</tr>");
    document.write("</table>");
  } else {
    document.write("<table>");
    document.write("<tr>");
    document.write("<td>" + data[j].month + "</td>");
    document.write("<td>" + data[j].rain + "</td>");
    document.write("</tr>");
    document.write("</table>");
  }
}

Answer №1

Develop a program that tracks monthly rainfall totals by creating an object with keys as the month names and values as the corresponding rain totals. Iterate through your array and accumulate the rain amounts into the appropriate total.

Ensure that only one table is generated; the loop should be responsible for constructing the rows.

var continueProgram = true;

function Month(month, rainfall) {
  this.month = month;
  this.rain = rainfall;
}

data = [];

monthsArray = ["January", "February"];

while (continueProgram) {
  var inputMonth = prompt("Enter the month", "");
  if (monthsArray.includes(inputMonth)) {
    var rainfallAmount = parseInt(prompt("Enter the amount of rain in milliliters for the month", ""));
    data.push(new Month(inputMonth, rainfallAmount));
  } else {
    alert("Invalid month");
  }
  continueProgram = confirm("Do you want to continue?");
}

var totalRainfall = data.reduce((obj, {month, rain}) => {
  if (month in obj) {
    obj[month] += rain;
  } else {
    obj[month] = rain;
  }
  return obj;
}, {});

document.write("<table>");
document.write("<tr><th>Month</th><th>Total Rainfall</th></tr>");

monthsArray.forEach(month => {
  document.write("<tr>");
  document.write("<td>" + month + "</td>");
  document.write("<td>" + totalRainfall[month] + "</td>");
  document.write("</tr>");
});
document.write("</table>");

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

The checkbox must be checked for the conditional form to appear, experiencing a Safari bug in version 12.2. No issues found in Chrome and Firefox browsers

My form includes a billing address section with a checkbox that automatically sets the shipping address to match the billing address. If the user unchecks the checkbox, another form will appear below for entering a different shipping address. The Checkbox ...

Communication through Collaboration Diagrams

For my software engineering project, I am working on creating communication diagrams. However, I am struggling with understanding how to draw if-then statements. Can anyone provide assistance with this? I have tried looking on YouTube for tutorials, but u ...

What are the steps to integrating a repository into the clean architecture design pattern?

I have been following Uncle Bob's clean architecture principles in developing my medical application's API. However, I am facing some challenges in determining where certain components should be implemented. Within my application layer, I have a ...

Incorporating a favicon into a Next.js React project

I'm currently working on integrating a favicon into a Next.js project that was generated using create-next-app. The favicon.png file is stored in the public folder, and I followed the instructions for serving static files outlined here. In my Layout ...

Easiest homemade variations and pairings

Imagine having a basic array like ["apple", "banana", "lemon", "mango"];. For example, if we were to find the straightforward hand-rolled combinations of this array, selecting 3 items, but allowing for repetition: let array = ["apple", "banana", "lemon", ...

Using properties to generate a header component in TypeScript

I am currently exploring TypeScript and incorporating it into a project for the first time. I'm encountering a challenge as I am not sure what to call this concept, making it difficult to search for solutions. If someone can provide me with the term, ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

Editing XHTML on the fly

Is there a tool available for non-technical individuals to edit hard-coded content in XHTML? I am interested in a solution similar to the integration of Pagelime with jEditable. Currently, my website is static and I am seeking a way for one person to log ...

Having trouble displaying the API response data on the screen in Next.js

I am currently experiencing an issue with my OCR API that is supposed to return text from a given image. The data is being received on the client side and can be seen in the console. However, for some reason, the element is not updating with the data. Bel ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...

Vercel and Express.js do not support hosting JavaScript files

I set up an Express.js server on Vercel with NowCLI, and in my index.js file, I configured it to serve all files in my dash/assets folder at assetsDash/ using app.use('/assetsDash', express.static(path.join(__dirname, 'dash', 'asse ...

What is the best way to showcase database values in a text-box using retrieval methods?

I am currently working on a database project that involves a webpage with 5 textboxes. One of these textboxes needs to display values from the database when it is in focus. I have the JavaScript and AJAX code to retrieve the data, but I am facing difficult ...

Adding new rows to an ng-repeat table in AngularJS with unique controls for each row, distinct from those

I have a table filled with JSON data using ng-repeat, similar to the example shown here: https://i.sstatic.net/Ffjuy.png Now, I am looking to insert new rows at the top of the table by clicking a button. However, these additional rows should contain edit ...

Steps for inserting an item into a div container

I've been attempting to create a website that randomly selects elements from input fields. Since I don't have a set number of inputs, I wanted to include a button that could generate inputs automatically. However, I am encountering an issue where ...

Utilize AJAX to update the database through a bootstrap modal interface

My current project involves creating a webpage to display database records with edit buttons that trigger bootstrap modals for user input and status changes. The goal is to use AJAX to update the database with any modifications made. However, I'm enco ...

Utilizing Vue JS to set an active state in conjunction with a for loop

Currently in Vue, I have a collection of strings that I am displaying using the v-for directive within a "list-group" component from Bootstrap. My goal is to apply an "active" state when an item is clicked, but I am struggling to identify a specific item w ...

Enhancing one's comprehension of precompiling JavaScript

var foo=1; function bar(){ foo=10; return; function foo(){} } bar(); alert(foo); As I delve deeper into the inner workings of JavaScript running on the machine, I stumbled upon this code snippet. Despite my best efforts, I am perplexed as to why the ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

Loading data from external URLs using AJAX and JSON

I am facing an issue, can someone please help? I have two websites and I want to send data between them. First website: var site_adres = $(location).attr('href'); var myArray = site_adres.split('/'); var site_adi_al = myArray[2]; ...

Issue encountered while attempting to establish an array in userdefaults: Thread 1 reports an error message stating "Trying to add non-property list object."

After some trial and error, I have managed to resolve the issue with saving arrays in userdefaults. Instead of attempting to save arrays with UITextViews directly, I learned that it is more effective to save their text content as strings. Here is a summary ...