Calculating the combined total and mean values within an object using JavaScript

I have a set of data in the following format:

{
"Dates": ["January", "January", "March", "March", "March", "November", "November"],
"Values": [45.6, 0.5, 59.3, 46.56, 2.21, 48.59, 5.5]
}

My goal is to combine the values in "Values" (averaging) by month

The output I am aiming for:

{
"Dates":["January", "March", "November"],
"Values":[23.05, 36.02, 27]
}

I have come across various discussions on this topic, such as the one here. However, I am unsure how to implement it for an object with arrays. Any suggestions would be greatly appreciated. Thank you

Answer №1

To achieve the desired outcome, follow these steps:

// Start by condensing the data into an object using dates as keys
const groupedData = data.Dates.reduce((accumulator, date, index) => {
  if (accumulator[date]) {
    accumulator[date].push(data.Values[index])
  } else {
    accumulator[date] = [data.Values[index]]
  }
  return accumulator
}, {});

// Next, transform the object into the required format
const finalResult = Object.keys(groupedData).reduce((accumulator, date) => {
  accumulator.Dates.push(date)
  accumulator.Values.push(groupedData[date].reduce((previous, current) => previous + current) / groupedData[date].length)
  return accumulator
}, {Dates: [], Values: []});

Answer №2

Here is a potential solution you can experiment with.

const data = {
  "Dates": ["January", "January", "March", "March", "March", "November", "November"],
  "Values": [45.6, 0.5, 59.3, 46.56, 2.21, 48.59, 5.5]
}

// Using Set to remove duplicate dates
const uniqueMonths = [...new Set(data.Dates)];

const result = {
  "Dates": uniqueMonths,
  "Values": uniqueMonths.map(month => {
    // Filter values for the current month
    const values = data.Values.filter((_, i) => data.Dates[i] === month);
    
    // Calculate the average value for the month
    return values.reduce((a, b) => a + b) / values.length;
  })
}

console.log(result);

Answer №3

If you want to streamline your tasks, consider breaking them down into smaller segments and utilizing functions for different purposes:

  • Organizing data into groups,
  • Calculating the average of an array,
  • Producing a final result by creating an object of groups.

const
    getAverage = array => array.reduce((a, b) => a + b) / array.length,
    groupBy = (keys, values) => {
        const groups = {};

        for (let i = 0; i < keys.length; i++)
            (groups[keys[i]] ??= []).push(values[i]);

        return groups;
    },
    getAverages = groups => Object.entries(groups).reduce((r, [month, values]) => {
        r.Dates.push(month);
        r.Values.push(getAverage(values));
        return r;
    }, { Dates: [], Values: [] }),
    data = { Dates: ["January", "January", "March", "March", "March", "November", "November"], Values: [45.6, 0.5, 59.3, 46.56, 2.21, 48.59, 5.5] },
    result = getAverages(groupBy(data.Dates, data.Values));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

How can I integrate the jQuery Plugin Mapael with Angular 5?

While exploring various methods that tackled the issue of integrating jQuery Plugins, I decided to start with the fundamentals. To begin with, I installed the jQuery plugin: npm i jquery Next, I included the TypeScript definition: npm install -d @types ...

Issue with passing parameter in Jquery AJAX request to controller function

Currently, I am integrating a Jquery AJAX Call into my MVC Application. Here is an overview of how my view is structured: <p> Name @Html.TextBox("Name") Date @Html.TextBox("Date") <input type="submit" id="SubmitName" value="Submit" /& ...

Trouble with Material-UI Textfield Hinttext Functionality

When designing a textfield according to job requirements, I encountered an issue. After assigning a background color to the TextField, the hintText disappeared. To resolve this, I had to manually set the z-index of the label. Now, the hintText is visible, ...

JavaScript's inability to properly export CSV data containing the "#" character has been causing issues

When exporting JSON data to CSV format and downloading it using JavaScript, everything typically works fine. However, there is a problem if the data contains the hash sign #. The function fails to export all the data in that case, for example: This is my ...

Ways to update a div periodically with new data fetched from a file - Here's How!

I am looking to auto-refresh a specific div every few seconds on my index.php page below. <?php session_start(); if (! check_write()) { redirect('testlogin.php'); return; } if (file_exists('lmt.json')) { $lmt = json_de ...

Trouble with component not refreshing upon store modification in Vuex

Summary: If you prefer, I have a video detailing my issue: https://youtu.be/Qf9Q4zIaox8 Concern with Navbar Component Not Updating on Store Change. The issue I'm facing involves the Navbar component not updating when there is a change in the store. ...

"Extracting JSON data from a URL and loading it into a

I am currently working on a project where I am retrieving data from a URL and storing it in an array. Here is the code snippet: $url = 'https://www.datastro.eu/api/explore/v2.1/catalog/datasets/orbits-for-current-comets-in-the-mpc-database/records?ord ...

Leveraging JSON for fetching distinct identifiers from a database

When a user hovers over a parent span containing an empty img tag, I use JSON and jQuery to retrieve the src of the image from the database. The issue arises when the retrieved src is applied to all looped span images on the same page, instead of each imag ...

How to extract a particular value from a JSON object using AJAX?

In my test.php file, I have implemented a code where ajax sends a request from index.php to this page. Within this page, I have created an array, converted it to JSON, and returned it as follows: <?php $arr = array( "status"=>200, "result"=>array ...

Switch up the positioning of elements using jQuery

My webpage contains multiple elements that are absolutely positioned with the CSS attribute "top." I am looking to adjust the top position of each element by 20px. This involves retrieving the current top position and adding 20px to it. The quantity of e ...

Is there a way to verify that all images have been successfully loaded following an

Is it possible to determine when all images have finished loading from an appended HTML source in order to trigger another function? $(document).ready(function () { $('a.load-more').click(function (e) { e.preventDefault(); $.ajax({ ...

Execute a PHP script to modify a section of a PHP file

I successfully implemented a piece of code into a PHP file by manually searching for the right section and inserting it. Now, I am looking to automate this process with an install script for my code. The ideal installation script would: 1. Copy the exist ...

What could be the reason for the bottom edge of my central diagonal image having a darker border?

I can't figure out why the border on the bottom edge of my image is darker. You can check out the demo here. To get a closer look at the issue, you can open a software like GIMP and zoom in on the following image to see the difference in values: http ...

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

Utilizing Subdirectories in a Command Manager

My goal is to organize my commands into sub folders, but for some reason my bot is not recognizing the commands inside those folders. Strangely, no error message is being displayed. const fs = require('node:fs'); const Discord = require('dis ...

Experiencing difficulty adjusting the width of a Tumblr post with JavaScript or jQuery?

Calling all coding experts! I've been working on customizing a Tumblr theme, and everything is looking good except for one issue. I'm struggling to adjust the width of photos on a permalink (post) page. Check out this link: You'll notice t ...

(Processing) Eliminating Previously Utilized Element from Array

Apologies for the poorly worded title. I'm working on a "War" game in Processing for my Programming course. I need help modifying my code to remove each used card from the deck/array. I've come across some references to "ArrayList" in online post ...

unable to access objects in JavaScript due to an error

The JSON data I received from PHP is shown in this image: https://i.sstatic.net/kj9QU.png Now, I need to access all the data from the JSON file. In my current situation, I am trying to compare the existing data with the JSON data. However, I encountered ...

What is the most effective way to prevent JavaScript from running during page load or when the document is ready

I am facing a challenge with my asp.net page. Whenever a textbox is left empty, I want to hide the entire page from the code behind. The issue arises because there is javascript and jquery code that runs on document ready, accessing data from certain page ...

Tips for inserting a DIV and SCRIPT from a single HTML template into a webpage

I'm working with an HTML template that contains a DIV with a button and a script with a function to call when the button is clicked: <div id="CLC_Form"> various text and checkbox inputs go here... <br> <input type="button" ...