What is the best way to tally json elements for every parameter?

My data consists of JSON objects with "Week" and "From" properties:

{
    "Week": 1145,
    "From": "IN1"
},
{
    "Week": 1145,       
    "From": "IN1"
},
{
    "Week": 1145,        
    "From": "IN2"
},
{
    "Week": 1146,
    "From": "IN1"
},
{
    "Week": 1146,
    "From": "IN2"
} 

I am trying to count the occurrences of each value in "From" for a given "Week". For example, for Week 1146, I would like to get IN1 = 1 and IN2 = 1, and for week 1145, IN1 = 2 and IN2 = 1.

I have created a function that iterates through my data store to tally up the occurrences of values based on a specified parameter:

countBy: function(param){
    var count = {};
    this.each(function(item){
        var type = item.get(param);
        if (Ext.isDefined(count[type])){
            count[type]++;
        } else {
            count[type] = 1;
        }                               
    });
    return count;
}

However, when I provide "Week" as the parameter, the function does not calculate the counts of distinct values in "From" for each WEEK; instead, it aggregates all occurrences under each week. For instance, it returns 1145 : 3 and 1146 : 2, while the desired outcome is 1145 : {IN1 : 2} and 1146 : {IN1 : 1}.

Your assistance in solving this issue would be greatly appreciated!

Answer №1

Include From in the list of parameters passed for successful execution.

Consider implementing the following code snippet:

countOccurrences: function(param1, param2){
    var count = {};
    this.each(function(element){
        var type = element.get(param1);
        var fromInput = element.get(param2);
        if (type in count){
            if (fromInput in count[type]) {
              count[type][fromInput]++;
            } else {
              count[type][fromInput] = 1;
            } 
        } else {
            count[type] = {};
            count[type][fromInput] = 1;
        }                               
    });
    return count;
}

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

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...

Guidelines for passing a value to a method within a method using JavaScript

I am currently exploring how jQuery can be used to select an element, retrieve an attribute, and assign it a new value. While I have successfully managed to select the element and extract the attribute, I am facing difficulty in setting the attribute using ...

The website encountered an error in loading with the error message "ENOTFOUND" in Cypress

All my cypress tests were running smoothly until one day they all failed to visit the target site. The error message that I received was: cy.visit() failed trying to load: https://mywebsite.com/accounts/login/ We attempted to make an http request to this ...

The necessary set of dependencies for implementing the Jackson mapper

Recently, I started working with Jackson in my coding exercises. As I was exploring the new version of the Jackson library on Fasterxml's website: Jackson, I decided to add the following dependencies to my Maven POM-file: <dependency> <gr ...

Exploring the functionalities of command line arguments in Vue.js

Is there a way to set command line arguments for a Vue.js application? I am utilizing Vue 3 on the frontend which interacts with a Python backend (Flask) using Axios. Currently, I am defining the baseURL for Axios in my main.js file as follows: import axio ...

Getting the ajax response by utilizing a custom attribute within a php loop is definitely a handy trick

Currently working on integrating ajax with php. I have a set of buttons within a loop, and I am trying to display or fetch data (number) in the correct place/div using the "attr" method in jQuery. However, it seems that it is not functioning as expected on ...

Tips on working with an array received from a PHP script through AJAX

I've been stuck with this issue for the past few hours and I'm hoping to find a solution here. What I'm attempting to do is something like the following: PHP: $errorIds = array(); if(error happens){ array_push($errorIds, $user['user ...

Utilizing Three.js to showcase large 3D images from a JSON file

I am in need of showcasing 3D images. I have a .obj file that is 80 MB in size which I converted to a json file size of nearly 75 MB. While using three js, I managed to display a rotating 3D image, but the main issue is the loading speed, which currently t ...

Tips for storing a list of files within another list as a JSON file in Python

After successfully parsing data from a website using BeautifulSoup in Python, I have managed to extract the desired information. Now, my goal is to save this data in a JSON file. However, when I attempt to do so with the existing code, the data gets saved ...

What is the best way to make a div pull its background image directly from the internet instead of using the cached version?

Running relevant Javascript every fifteen minutes to fetch the appropriate image from the internet: document.getElementById('weatherbug').style.background = "url('http://tinyurl.com/jwltx5s') repeat scroll -1px -24px transparent"; The ...

Encode and decode large integers in JSON format without any loss of data

According to the PHP documentation, long integers in a data structure will be converted to floats when using json_decode. To preserve them as strings instead, you can utilize JSON_BIGINT_AS_STRING. Subsequently, utilizing JSON_NUMERIC_CHECK when encoding s ...

Struggling with calling rerenderEvents in FullCalendar using JQuery after a successful AJAX request

I seem to be encountering an issue where the calendar does not update after a POST request. Everything works smoothly until that point: $('#calendar').fullCalendar({ ... select: function (startDate, endDate) { $.ajax({ ...

In PHP, there may be instances where certain words are not displayed properly, even if they do not

I am facing an unusual issue where I am extracting data from SQL Server using Xammp server and displaying it in a browser using PHP with JSON output. Some of the strings that I want to display on the browser have descriptions like: "**Delightfully warming ...

How do you typically approach testing Cloud Code on Parse?

While working on developing a substantial amount of business logic in webhooks like beforeSave/afterSave/etc. using Parse.com, I have encountered some challenges as a JavaScript/Parse beginner. The process seems somewhat tedious and I'm questioning if ...

Attempting to grasp the intricacies of the express Router functionality

I'm a beginner with Node.js and I currently have three JS files: The Index.js file has the following code: var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, r ...

Using PHP to generate JSON arrays from MySQL data for displaying in Highcharts

Need help with configuring Json output for my highchart scatter plot? Check out this example. Here is the desired Json output: [{ "name": "Female", "color": "red", "data": [{ "name": "Anna", "x": 161.2, ...

The behavior of having two submit buttons within the $document.ready(function) in Jquery

In my code, I have implemented the behavior of two buttons, button1 and button2, within a $(document).ready(function). Whenever either button is clicked, an alert() function should be triggered. However, it seems that only button2 is functioning properly w ...

Cannot convert a Java.lang.String value to a JSONObject in JSON format

I have been working with an API (link here) that provides a JSON response. Recently, I encountered an issue while parsing this JSON data. It was functioning properly earlier, but something seems to have changed either in my API or Java code. Below is the ...

ReactJS requires HTTP server to transpile babel code before running

I am a beginner when it comes to working with reactjs and I am currently in the process of setting up babel to execute babel code without having to serve HTTP files. Following the instructions on the Package Manager, I have successfully installed it along ...