What is the best way to generate a random temperature value for every day of a month using an array with 30 date/day items?

In a hypothetical scenario where there are 30 days in a month, temperatures ranging randomly between 7 and 16°C are assigned to each day. Below is the code snippet used:

let arrMonth = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
    22, 23, 24, 25, 26, 27, 28, 29, 30
]

let temperature = Math.floor(Math.random() * (16 - 7 + 1)) + 7;

for (let i = 0; i < arrMont.length; ++i) {
    arrMonth[i] = temperature;
    console.log(arrMonth[i]);
}

The issue reported is that only the temperature for the last day is displayed. Can you spot the mistake I made?

Output on the console:

30: 11

Answer №1

An easy enhancement to your existing code is to convert your variable into an arrow function, like this:

const temperature = () => (Math.floor(Math.random() * (16 - 7 + 1)) + 7);

By doing this, every time you call 'temperature()', you'll receive a fresh value.

let arrMonth = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
]

const temperature = () => (Math.floor(Math.random() * (16 - 7 + 1)) + 7);


for (let i = 0; i < arrMonth.length; ++i) {
    arrMonth[i] = temperature()
    console.log(arrMonth[i])
}

Answer №2

We are looking at a request from the original poster that involves a task related to mapping in JavaScript.

However, since the original poster also desires to display dates and days with precision, it is recommended to follow a separation of concerns approach, where each task is handled by a distinct function.

This allows flexibility for the original poster to experiment with various tasks and customize them according to their requirements...

function getRandomValueFromTemperatureRange() {
  // generates random values between 7 and 16 (inclusive).
  return (Math.floor(Math.random() * 10) + 7);
}

function createTemperedDateItem(date) {
  return {
    date,
    temperature: getRandomValueFromTemperatureRange(),
  };
}
function renderTemperedDateItems(dateList) {
  const listRootNode = document.createElement('dl');

  dateList.forEach(dateItem => {
    const { date, temperature } = dateItem;

    const dateNode = document.createElement('dt');
    const temperatureNode = document.createElement('dd');

    dateNode.title = 'Date within Month';
    temperatureNode.title = 'Temperature in °C';

    dateNode.textContent = date;
    temperatureNode.textContent = temperature;

    listRootNode.appendChild(dateNode);
    listRootNode.appendChild(temperatureNode);
  });
  document.body.appendChild(listRootNode);
}

const arrMonth = Array.from(
  { length: 30},
  (elm, idx) => (idx + 1)
);
console.log({
  arrMonth,
  temperedDateList: arrMonth.map(createTemperedDateItem),
});

renderTemperedDateItems(
  arrMonth.map(createTemperedDateItem)
);
dl { margin: 0!important; }
dl::after { clear: both; display: block; content: ''; }
dt { float: left; }
dd::after { display: inline; content: ' °C'; }

body { margin: 0 0 100px 0!important; }
.as-console-wrapper { max-height: 100px!important; }

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

In my Node.js application using Express and Passport, I encountered an issue where res.locals.users is functioning properly but the data it

I'm currently working on an application using NodeJS, Express, and Passport. However, I've encountered an issue when trying to display user data in the views. While I am able to retrieve the ObjectID of the user from res.locals.user, accessing s ...

Substituting terms using their position indices

I am currently developing a writing tool that checks certain words for markup using my API. The concept is to highlight words as the user types by adding a red underline to matching words. To start, I have implemented the following function to determine w ...

The JQuery script has not been initialized, causing the function to not activate

I keep encountering this error message: Uncaught ReferenceError: toggleOptionsVisibility is not defined at HTMLSelectElement.onchange Here's the HTML code I'm working with: <div> <label asp-for="Type"></label&g ...

JavaScript has been used to modify a cell's URL in jqGrid

Currently, I am utilizing struts2-jqgrid along with JavaScript. After the jqgrid has finished loading, it retrieves <s:url var="updateurl" action="pagosActualizar"/>. Subsequently, in the HTML view source, jqgrid generates options_gridtable.cellurl = ...

How can one determine if a DOM element has been generated dynamically?

Some of the content on this page is dynamically created after an ajax request, while other content was pre-loaded when the page refreshed. When I click on an anchor tag, I need to know if it was created dynamically or not. I did manage to solve this issu ...

What sets apart accessing an array using a pointer from accessing a regular variable through a pointer?

I have been diving deeper into my C programming skills and here is a code snippet I wrote to explore pointers: #include "includes.h" int main() { char *array[1]; array[0] = "cloud"; char *ll[1]; ll[0] = array[0]; int n = 20, *pointer; ...

The ins and outs of function returns and callback mechanisms

I'm encountering an issue related to the order of my functions and I can't figure out the reason behind it. When I hover over the call for function_2 inside the first function, VSCode shows me the result as Promise<void>, and the console p ...

Using a Svelte click event to toggle a boolean value in an array from a div

How can I modify the toggle functionality to work on any click event, not just on a button, in order to trigger a state change regardless of the element clicked? ToolBar.ts export default class ToolBar { options:Array<ToolBarOptions>; const ...

In search of a React.js/Redux OpenID library or example, particularly focused on Steam OpenID integration

Currently, I am developing a Node/Express REST + React/Redux application that requires Steam OpenID for authentication. Despite searching extensively for tutorials, libraries, or example code related to Steam OpenID (or any other OpenID), I have come up em ...

Error with Laravel and Vue template integration

I have recently started using Vue in Laravel 5.3 and I am able to retrieve data through a jQuery AJAX request within Vue. However, I am facing difficulties with displaying the data. Below is my current script in the view: <li> <!-- inner men ...

What is the best way to access an item within an item using HTML and AngularJS?

I attempted to retrieve a value from two dynamic objects using AngularJS. <div ng-controller="SampleController"> <div> {{item['111']['price']}} </div> within the SampleController $scope.item={111:{price:"232"},112:{ ...

How can I use Ajax to populate a div with data from a php script?

Is there a straightforward method to populate a div by fetching a PHP script (and sending data like POST or GET) to determine what data should be returned? I'm searching for a solution that doesn't rely on a library... All I seem to come across ...

Tips on how to make the cursor blink in an input text box after tab switching

Whenever I click the button, the cursor in the input field blinks. However, the issue arises when I switch to another tab and return to this tab - the cursor is no longer in position and I have to click the input field again. Even after switching tabs an ...

Iterate through the classes for updates rather than focusing on individual id fields

I am currently working on creating a function that can refresh data with an AJAX call for multiple instances of a class within a single page. The function functions perfectly when there is only one instance on the page: $(document).ready(function() { ...

JXBrowser comparable

In a Java project of mine, I have been utilizing JXBrowser to showcase Google Maps for route tracing purposes. However, the license for JXBrowser has recently expired after just one month. Unfortunately, simply requesting another license is not an option ...

Retrieve a dynamic value from an object

Is it possible to dynamically pass a context from the server to the client so that the client can retrieve a value from an object more efficiently? For example, the server sends an object with a key-value pair like this: "booking__validating_carrier_ ...

When using the Google Maps API fetch() method, the response is empty. However, when accessing the same

I am currently working on extracting the "photo_reference" from the JSON data provided below; { "html_attributions" : [], "results" : [ { "formatted_address" : "Bandar Seri Begawan, Brunei", "geometry" : { "locati ...

What is the best way to convert a char array in order to compare it with an unsigned char array?

I am attempting to convert s2 in order to pass the test. Printable characters along with unsigned char values are being stored together in s3. s2 serves as a verification string for checking if printable characters are correctly loaded into s3. #include ...

Explicitly linking controllers with Angular scope objects

According to the documentation on AngularJS Understanding controllers: Linking Controllers to Angular Scope Objects Controllers can be linked to scope objects implicitly through the ngController directive or $route service. These two methods are commo ...

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...