A guide to categorizing and tallying JSON data based on multiple keys within the past 30 days using JavaScript/jQuery

I am facing an issue while trying to display a chart and extract specific data from an array.

My goal is to generate a chart based on three columns in a JSON array: Source, Campaign, and Date. The process involves grouping the data, counting it, and then visualizing it on the chart. However, I am encountering difficulties as the outcomes are returning NaN values instead of the desired results. Here is the JSON array that I am working with:

results = [{
    "utm-source": "direct",
    "utm-campaign": "nothing",
    "Date": "2019\/05\/10"
},
{
    "utm-source": "direct",
    "utm-campaign": "nothing",
    "Date": "2019\/08\/08"
},
{
    "utm-source": "direct",
    "utm-campaign": "nothing",
    "Date": "2019\/08\/09"
},
{
    "utm-source": "direct",
    "utm-campaign": "nothing",
    "Date": "2019\/08\/12"
},
{
    "utm-source": "google",
    "utm-campaign": "spring_sale",
    "Date": "2019\/08\/21"
},
{
    "utm-source": "facebook",
    "utm-campaign": "spring_sale",
    "Date": "2019\/08\/21"
},
{
    "utm-source": "email",
    "utm-campaign": "spring_sale",
    "Date": "2019\/08\/21"
}]

Despite my attempts, I have not been able to achieve the desired outcome using this code:

var today = new Date();

var year = today.getFullYear();
var month = today.getMonth();
var date = today.getDate();

// build the last 30 days date array
var last30days = [];
for(var i=0; i<30; i++){
   var day = new Date(year, month, date - i);
   day = day.toISOString().split("T")[0].replace(/-/g,"/")
   last30days.push(day);
}
console.log(last30days);

var finalArray = [];
last30days.forEach(function(day,dayIndex){
   results.forEach(function(result,resultIndex) {
       var found = result.Date.indexOf(day);
       console.log(found);
       if(found == 0) {
           //console.log(result);
           finalArray[result.utm_source] += result.Lead_Source;
       } else {
           finalArray[result.utm_source] += "0";
       }
   });
});

The anticipated output should resemble this: https://i.sstatic.net/gbvMT.jpg By comparing this array to another one containing the last 30 days, displaying and tallying the number of leads for direct nothing or facebook spring_sale. For the days without any leads, it should return 0 and represent that on the chart for the corresponding campaign and source displayed only once. Furthermore, the expected format of the array is as follows:

{
    "direct": {
        "nothing": {
            "2019/07/24" : "0",
            "2019/07/25" : "0",
            ...
            "2019/08/22" : "0"
        }
    },
    "google": {
        "spring_sale": {
            "2019/07/24" : "0",
            "2019/07/25" : "0",
            ...
            "2019/08/22" : "0"
        }
    },
    "facebook": {
        "spring_sale": {
            "2019/07/24" : "0",
            "2019/07/25" : "0",
            ...
            "2019/08/22" : "0"
        }
    }
}

Answer №1

If your goal is to group data by the utm-source field specifically, then you can achieve this with the following code snippet:

const numCounts = {};
results.forEach(result => {
  numCounts[result["utm-source"]] = (numCounts[result["utm-source"]] || 0) + 1;
});

The resulting output will be:

{ direct: 4, google: 1, facebook: 1, email: 1 } 

This process is similar in concept to the one discussed in How to count duplicate value in an array in javascript, but it involves objects instead of string arrays.

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

Calculate the total width of all images

I'm on a mission to calculate the total width of all images. Despite my attempts to store image widths in an array for easy summing, I seem to be facing some challenges. It feels like there's a straightforward solution waiting to be discovered - ...

Is it possible to filter an array of data using a dropdown in Angular without using a pipe?

I am facing an issue with filtering data based on the selected dropdown item. Currently, it only filters the data once when I select a filter, and after that, it always returns an empty result. Here is an example of the code: <select class="select" (c ...

In Android, there are instances where multiple HTTP requests are made with just one call, especially when there

Currently, I am working on establishing a HTTP URL connection for uploading JSON in an Android application. The upload request is being handled by an Intent Service, with a broadcast receiver set up to detect network changes and trigger the Intent Service ...

Embed HTML code into a React/Next.js website

I've been given the task of enhancing the UI/UX for an external service built on React (Next.js). The company has informed me that they only allow customization through a JavaScript text editor and injecting changes there. However, I'm having tro ...

The jQuery script seems to be failing to execute

Recently, I have been delving into the world of jQuery. However, after adding my code, the functions I set up are failing to run. Strangely enough, just two weeks ago everything was running smoothly without any errors in linking files within my HTML docume ...

Can you explain the significance of this async JavaScript server application error?

While working on a weather app website connected to another site through a server, I encountered an issue with asynchronous JavaScript. Upon running the code, I received an error message stating "uncaught syntax error: unexpected end of input" in the last ...

Mastering the ins and outs of ngStorage in AngularJS

Imagine a web page featuring a form that allows users to input multiple entries before submitting. As each entry is added, a summary of the data entered is displayed in a table at the top. Once all entries are completed, the user can then proceed to submit ...

Escaping latitude and longitude coordinates using PHP

I am looking to include longitude and latitude values in a json file. However, the current code I have escapes the values and adds quotation marks. Example of json output{"votes":["{\"lat\":\"51.426799\",\"lng\":\"-0.331 ...

The Google Maps application is experiencing an issue with rendering maps

Here is my code without the google map key. I am not receiving any errors, but the map is not showing up. What could I be missing? To test it out yourself, you will need to add your own map key which you can obtain from here. <!DOCTYPE html> <h ...

Using Typescript to change a JSON array of objects into a string array

I'm currently working with the latest version of Angular 2. My goal is to take a JSON array like this: jsonObject = [ {"name": "Bill Gates"}, {"name": "Max Payne"}, {"name": "Trump"}, {"name": "Obama"} ]; and convert it into a st ...

jQuery Ajax error 403 (unlike XMLHttpRequest)

Recently, I encountered an issue with two Ajax calls in my code. One of the calls was implemented using XMLHttpRequest and the other one using jQuery. Surprisingly, the first call completed successfully without any errors. However, the second call, which s ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

The requestify Node module encounters issues when the body contains special characters

My current project involves the use of node.js and a library called requestify. Here is the snippet of code causing some trouble: console.log('body'); console.log(body); return new Promise(function (f, r) { requestify.request(myurl, { ...

Using window.open in Google Chrome results in multiple tabs being opened instead of just one

I have a dynamic input field with a search button. Initially, only one tab is opened when I click the button. But after saving and clicking it again, multiple tabs open for the same URL. The number of tabs is equal to the number of dynamic input fields cre ...

Different ways to categorize elements of Timeline using typescript

I have some code that generates a timeline view of different stages and their corresponding steps based on an array of stages. Each stage includes its name, step, and status. My goal is to organize these stages by name and then display the steps grouped un ...

Which sorting algorithm is most suitable for handling strings, numbers, or a combination of both in JavaScript?

This situation is quite intriguing to me. Suppose we have an array defined as: var x = [1, 50, 2, 4, 2, 2, 88, 9, 10, 22, 40]; Now, if we run the code x.sort();, it will fail to sort properly. On the other hand, if the array is defined as: var x = ["dog ...

Creating a MongoDB schema in NodeJS with fields named using the special character '$' (dollar sign) involves following a specific set of steps

I need to transfer information to a mongo database and an API endpoint from a node.js application. The JSON format required by the API is as follows: { "$type" : "$create_account", "$api_key" : "a167abc7760c6dc3", "$user_id" : "INSERT_USER_ID" ...

Implementing div elements in a carousel of images

I've been working on an image slider that halts scrolling when the mouse hovers over it. However, I'd like to use div tags instead of image tags to create custom shapes within the slider using CSS. Does anyone have any advice on how to achieve th ...

PHP array containing images with redirection

There is a file called foo.txt that contains the locations of various pictures. http://foo/bar1.png http://foo/bar2.png http://foo/bar3.png When displaying these pictures using an array, some are missing and the server redirects to the same 404 image for ...

Issue with Javascript variables

In Javascript, I have an array of strings that I need to use for loading images on my page through AJAX. After each image is loaded, there are additional tasks to be performed which include sending a HTTP request to delete the image. Below is the code I c ...