Merge the JSON data of homerun statistics with corresponding date information

The task at hand involves extracting "Dates" and "homeruns" from the provided .json file. The goal is to combine matching Dates together and sum up the homeruns corresponding to those dates. Currently, I have managed to display the combined Dates with their matching dates, but the Homeruns are not being added up; instead, they are just stacking next to each other. For instance, for Date: "1985", Hits: "3", Homeruns: "101".

chart.json

[{"Date": "1903", "Hits": "0", "Homeruns": "1"}, {"Date": "1903", "Hits": "1", "Homeruns": "2"}, ... 

JS

function chartPage()
        {
            $.ajax(
            {
                url: 'chart.json',
                data:
                {},
                dataType: 'json',
                success: function(data)
                {
                    var stringy = JSON.stringify(data);
                    var objects = $.parseJSON(stringy);
                    var categories = new Array();
                    var groupedObjects = new Array();
                    var i = 0;
                    _.each(objects, function(obj)
                    {
                        var existingObj;
                        if ($.inArray(obj.Date, categories) >= 0)
                        {
                            existingObj = _.find(objects, function(o)
                            {
                                return o.Date === obj.Date;
                            });
                            existingObj["Homeruns"] += obj["Homeruns"];
                        }
                        else
                        {
                            groupedObjects[i] = obj;
                            categories[i] = obj.Date;
                            i++;
                        }
                    });
                    groupedObjects = _.sortBy(groupedObjects, function(obj)
                    {
                        return obj["Homeruns"];
                    }).reverse();
                    // print results for testing
                    _.each(groupedObjects, function(obj)
                    {
                        var output = '';
                        _.each(obj, function(val, key)
                        {
                            output += key + ': ' + val + '<br>';
                        });
                        output += '<br>';
                        $('#results').append(output);
                        console.log(output);
                    });
                }
            });
        }

Answer №1

It seems that homeruns are not adding up properly, which could be due to adding strings together. A simpler solution would be:

_.each(data, function (item) {
  if (!tempHomeruns[item.Date]) {
    tempHomeruns[item.Date] = 0;
  }
  tempHomeruns[item.Date] += parseInt(item.Homeruns, 10);
});

_.each(tempHomeruns, function(item, key) {
  homeruns.push({
    name: key,
    y: item
  });
});

For the Highcharts code:

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
  xAxis: {
    type: 'category'
  },
  series: [{
    data: homeruns
  }]
});

You can view a live demo here. For an example with both Hits and Homeruns, click here.

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

Converting a string containing multiple objects into an array with unique keys

I have a string with multiple objects and I need to add these objects into an array with different values. The data is received from the cart, so the number of objects can vary. For example: {"hidden_product_name":"productA","productId":"120","product_sk ...

Navigating through a collection of objects

My array consists of objects, each having the following structure: var car = { make: "", model: "", price: "" } I am attempting to iterate through each object and check if a specific property is defined in this manner: for (i = 0; i <= ...

Including the Advanced Custom Fields (ACF) PHP value into a JavaScript array within a foreach loop

I am currently working with a code snippet that involves the variable $v. Each $v holds a specific string value (ex: icon1, icon2, icon3, icon4): <script type="text/javascript"> var vArr = new array(); </script> ...

What's the best way to pass parameters through Higher-Order Components in React?

my custom component App import React, { Component } from "react"; import City from "./City"; import withDataLoader from "./withDataLoader"; const MyApp = () => { const MyCity = withDataLoader( City, "https://5e5cf5eb97d2ea0014796f01.mockapi ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

Managing all mouse interactions simultaneously in ReactJS

I've successfully created a button: <button className='collapse-button' onClick={() => {setTopNavigationBarCollapse(!topNavigationBarCollapse)}}>&#9776;</button> Now, I'm wondering if there's a way to call the s ...

What is the best method for individually toggling multiple displays in React?

Currently, I am pulling multiple posts from an API request and I want each post to have a toggle option. The issue is that when you click on the "Show More" toggle, it expands all the posts at once. I am using the NPM react-toggle-display package for this ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

Fade in an image using Javascript when a specific value is reached

Here's the select option I'm working with: <div class="okreci_select"> <select onchange="changeImage(this)" id="selectid"> <option value="samsung">Samsung</option> <option value="apple">App ...

An efficient strategy for extracting JSON property values from deeply nested JSON responses using C#

I have received a JSON string as an HTTP response, which I am converting to a JObject. The response includes a "sessions" node with multiple session values. Each session contains "events" with one or more "events", each of which has a "Type" and "Arbitrary ...

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

Implementing Vue.js click event behavior on a component within the template

Encountering an issue while developing Vue's template onclick event. Trying to open a module when clicking a file, I have looked at some samples with native code, but it does not quite fit into my code and I cannot reach the console. Here is my code: ...

A comprehensive guide to leveraging synchronous execution of setTimeout in JavaScript

Can the desired output shown below be obtained using setTimout? If it is possible, please provide your insight: console.log("1st"); setTimeout(() => { console.log("2nd"); },0); console.log("3rd"); The expected output should be: 1st 2nd 3rd ...

How can I verify the JSON structure of my Rails 3.0.11 controller using Rspec?

Despite my efforts, I can't seem to figure out how to make Rspec send the correct content-type for testing my JSON API. My setup includes the RABL gem for templates, Rails 3.0.11, and Ruby 1.9.2-p180. When I use curl to test, everything seems to work ...

Storing events from FullCalendar into a database

I have been working on implementing the following markup: Within my project, I am using a fullcalendar instance. When a user clicks on a day, it triggers the dayClick callback function which opens a bootstrap modal. The user can then enter a title, start/ ...

Access a file from the local system using JavaScript within a Django application

I am encountering an issue with fetching a .txt file in a folder using the fetch() function in JavaScript within a Django project. Whenever I try to call the file with fetch, a Django error occurs. (index):456 GET 404 (Not Found) The file I am trying to ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

Is there a way to verify file types using Vuelidate?

Is there a way to validate file types like png, jpg, and jpeg using Vue.js's Vuelidate library? ...

Developing a collection of reusable components in a Javascript bundle for enhanced efficiency

I currently have a backend rendered page (using Django) that I want to enhance by incorporating components from PrimeVue and a markdown editor wrapped as a Vue component. Previously, we utilized some simple animations with jQuery which we included directly ...

Difficulty in retrieving nested objects from JSON response using ReactJS and axios

Encountering difficulties in extracting data from the JSON response retrieved from the wagtail CMS: { "meta": { "total_count": 1 }, "items": [ { "id": 13, "meta": { "type": "home.HomePage", "detail_url": "http://l ...