Organize data by date and determine the highest and lowest temperature values within a JSON array of objects

I recently obtained weather forecast data from an API, which can be accessed here: Weather Forecast Data

This dataset includes weather predictions for 5 days, with updates every 3 hours. My goal is to organize the data by date and determine the minimum and maximum temperatures for each day.

The desired output format is as follows:

[
{
"date" : "2021/7/2",
"min_temp": 282.06,
"max_temp": 300.05
},
{
"date" : "2021/8/2",
"min_temp": 282.06,
"max_temp": 300.05
},
{
"date" : "2021/9/2",
"min_temp": 282.06,
"max_temp": 300.05
},
{
"date" : "2021/10/2",
"min_temp": 282.06,
"max_temp": 300.05
},
{
"date" : "2021/11/2",
"min_temp": 282.06,
"max_temp": 300.05
},
]

I have attempted to group the dates using the following code:

var result = [];
            newArray.reduce(function (res, value) {
                if (!res[value.dt_txt]) {
                    res[value.dt_txt] = { dt_txt: value.dt_txt, value };
                    result.push(res[value.dt_txt])
                }
                return res;
            }, {});

However, this code only groups the dates and does not calculate the min/max values for each day. I am currently looking for a solution to address this issue.

Answer №1

Calculating min and max values using a normal loop instead of the reduce method as it may be simpler for this particular task.

var tempResult = {};
var finalResult = [];

// Creating unique objects with dates as keys
newArray.forEach(function(item) {
  var minTemp = item.main.temp_min;
  var maxTemp = item.main.temp_max;
  if (!tempResult[item.dt_txt]) {
    tempResult[item.dt_txt] = {
      "min_temp": minTemp,
      "max_temp": maxTemp
    }
  } else {
    var previousMin = tempResult[item.dt_txt].min_temp;
    var previousMax = tempResult[item.dt_txt].max_temp;
    tempResult[item.dt_txt] = {
      min_temp: minTemp < previousMin ? minTemp : previousMin,
      max_temp: maxTemp > previousMax ? maxTemp : previousMax
    }
  }
})
console.log(tempResult)
// { 2021-02-07: {min_temp: 292.25, max_temp: 300.25} }

// Converting to array object
for (var date in tempResult) {
  finalResult.push({
    "dt_txt" : date,
    "min_temp": tempResult[date].min_temp,
    "max_temp": tempResult[date].max_temp
  })
}

console.log(finalResult)
// [ {dt_txt :'2021-02-07', min_temp: 292.25, max_temp: 300.25}, {...} ]

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 issue arises when attempting to use the cancel button to exit the editing modal for an item within an ng-repeat loop, while

In my project, I have set up a ng-repeat loop to display blocks that can be edited in a modal window. The goal is to allow users to make changes and then cancel the window to discard any modifications. While the modal window is functioning correctly and ed ...

In TypeScript, the choice between using `private readonly` within a class and

I have been contemplating the best method and potential impacts of referencing constants from outside a class within the same file. The issue arose when I was creating a basic class that would throw an error if an invalid parameter was passed: export cla ...

Calculate the ages of several individuals by inputting their birthdates on a date

When dealing with multiple inputs, I can calculate the date for a single input. However, when there are more inputs, how do I go about doing that? One setfield includes a name, DOB, and AGE. The age must be calculated based on the selected DOB... the iss ...

What is preventing Backbone from triggering a basic route [and executing its related function]?

Presenting My Router: var MyRouter = Backbone.Router.extend({ initialize: function(){ Backbone.history.start({ pushState:true }); }, routes: { 'hello' : 'sayHello' }, sayHello: function(){ al ...

Setting the lang attribute on the html element in Nuxt: A step-by-step guide

Customizing the nuxt.config.js file allows for personalization of the head contents by adding meta tags and other elements: module.exports = { /* ** Headers of the page */ head: { title: 'amazing title', meta: [ { charset: ...

What is the best way to apply a class to the grandparent div of an element in AngularJS?

Currently, I have a dynamically generated list of tests: <script id="TestsTemplate" type="text/ng-template"> <article class="tests-main"> <section class="tests"> <div class="test" ng-repeat="test in ...

Use the map function to pass onClick to every individual image

I need help passing an onClick function to each thumbnail image created with the map function. The goal is for the main image to change to the clicked thumbnail when a user selects it. Currently, it seems like the onClick function is being triggered witho ...

Ways to conceal components upon clicking a different element

Struggling to make this jQuery function properly. I have a form with all fields contained in a div.form-group. The subscribe button is identified by the id subscribe. I'm aiming to hide the form fields when clicked, but my JavaScript doesn't see ...

Unable to modify the value of data using the data() method

Just a basic HTML code snippet <div class="this" data-info="false"></div> $('.this').data('info'); This will correctly output: false $('.this').data('info', 'true'); data-info remains u ...

How to Access Nested Arrays in ReactJS

As a ReactJS beginner, I've been making progress with my project. However, I've hit a roadblock that seems to be my final hurdle. Here's what I'm trying to achieve: TV Show - Simpsons Name: Bart Simpson, Gender: Male Name: Homer Simp ...

How to send JSON data to Node.JS using jquery

I'm working on sending the following data to my node.js server: { "SKU": { "comment": { "name": "23", "com": "32" } } } The plan is to store this information in a text file. The SKU, name, and com values are all s ...

Is it possible to only make the text in a Bootstrap button act like a link, instead of the whole button itself?

As I start learning HTML and CSS with the help of Bootstrap, I'm encountering an issue with button functionality. The text within the button is acting like a link, but the entire button should be clickable. I'm not sure if I need more than just t ...

Generating JSON array objects dynamically in JavaScript code

Need help with organizing my code let newArr = []; $.post( "/reports/search", { query:'*'},function(data) { for(let i=0; i<data.length; i++) { newArr[i].value = data[i].name; newArr[i].data = data[i].id; } },'json ...

What strategies can I employ to utilize Wikidata for creating a Siri-inspired platform?

My interest lies in exploring the functionality of a Siri-like service, specifically focusing on the first part. What I'm looking for is the ability to search for things like: "the social network" "beethoven" "bad blood taylor swift" With results ...

Conceal elements within a div using the 'elementFromPoint' function

In my HTML, I have a div that contains an icon and some text. I want to make it so that when I hover over the div with my mouse, only the div itself is visible to the 'elementFromPoint' function. How can I achieve this? Here is an example of th ...

performing a calculation using an array of timestamps

Performing calculations on a single timestamp is simple: from datetime import datetime timestamp = 1456741175 dt = datetime.fromtimestamp(timestamp) print(dt.day) # Week day number print(dt.weekday()) print(dt.minute) print(dt.second) But what if the tim ...

Replicate a click using jQuery to retrieve a filtered multigallery based on the URL

I have a website that was built using Elementor for a photographer. The site features an Elementor Multigallery with a filter at the top. I am looking to create external links that will direct users to specific subpages showing only filtered items. For ex ...

Implementing a personalized filter onto the footer of an AngularJS UI Grid

After successfully creating a custom filter for my ui-grid that limits decimal numbers to two places and exporting it as a pdf using ui-grid-exporter, I encountered an issue. The filter works fine when exporting the main ui-grid but fails to apply within t ...

Optimal method for transforming the values of an object or array in JavaScript

I have a group of values that need to be transformed into new values using a legend. The process might sound confusing at first, but it will become clear shortly. To achieve this, I've relied on associative arrays or objects in JavaScript to serve as ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...