Show occurrences of an array categorized by date using JSON format

I'm interested in analyzing a JSON array to find the occurrences of a specific item by date. Let me demonstrate with the following JSON example:

"data": [
    {
      "tags": [
        "foo",
        "bar",
        "hello",
        "world",
        "alice"
      ],
      "date": [
        1402876800000
      ],
      ...
    },
    {
      "tags": [
        "foo",
        "world",
        "alice"
      ],
      "date": [
        1402963200000
      ],
      ...
    }

My goal is to create a function that takes a tag as input ('foo' for instance) and displays how many times that tag appears on a particular date in the HTML. So if we call tagOverTime('foo'), the result would be something like this:

06/16/14 - 14 occurrences

06/17/14 - 8 occurrences

I also intend to format the dates, but I believe I can handle that part using toLocaleDateString(). Currently, I am able to iterate through the array, but not much beyond that. Here is my progress so far:

$.getJSON('mydata.json', function(data) {

function containsObject(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i] === obj) {
            return true;
        }
    }

    return false;
}

function tagOverTime(tagToSearch) {
  var output="<h4>" + tagToSearch + "</h4><ul>";
    for(var i = 0 ; i< data.data.length; i++){
        var obj = data.data[i];
        var tagsArray = obj["tags"];
          // make sure tag array isn't empty
          if( tagsArray != undefined ) {
          // then iterate through it
          for(var j = 0; j < tagsArray.length;j++ ){
            // if that tag exists in the given tags array, check its date and count up somehow
            if(tagsArray[j] == tagToSearch){
              output+='<li>' + obj.date + '</li>';
            }
          }
        }
    }
  output+="</ul>";
  document.getElementById("output").innerHTML=output;
}

tagOverTime('foo');

Although the code currently generates an unordered list of dates, it doesn't accurately calculate the occurrence counts for specific dates. I acknowledge this flaw as I wrote the code and am now seeking a solution to effectively tally up occurrences on individual dates.

Answer №1

function searchTagOccurrences(tagToFind) {
    var result ="<h4>" + tagtofind + "</h4><ul>";
    var byDate = {};
    for (var i = 0; i < data.data.length; i++) {
        var obj = data.data[i];
        var tagsArray = obj.tags;
        if (tagsArray && containsObject(tagToFind, tagsArray)) {
            if (byDate[obj.date]) { // Have we already seen this date?
                byDate[obj.date]++;
            } else { // No, initialize it to 1
                byDate[obj.date] = 1;
            }
        }
    }
    for (var date in byDate) {
        result += '<li>' + date + ' - ' + byDate[date] + ' occurrences</li>';
    }
    result += '</ul>';
    document.getElementById("output").innerHTML=result;
}

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

Applying CSS classes to a custom AngularJS directive: A step-by-step guide

Need to have a CSS class called tab for the nav HTML element, which will be used as a directive: <nav tab></nav> The expected interpretation is: <nav class="tab"> <a></a> <a></a> <a></a> ...

Combining two arrays in PHP based on a common key and value

Looking to combine two arrays based on a common key and value. The merging criterion is if they share the same ur_user_id. The second array (array2) adds extra data to the first array (array1), resulting in new_array.length being equal to array1.length. Es ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

Expecting a volumetric result can be deceiving when dealing with objects that have three flat

The problem at hand: When subtracting a cube from a sphere, an interesting result occurs where the z axis maintains its volume while the y and x axes create flat disks. This peculiar outcome is puzzling to me as I utilize the typical subtraction method wi ...

Choose an element based on its position in the index (multiple elements with the same class)

Can you use Javascript or jQuery to select an element by its index? For example: <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> If I have 4 elements with ...

Establishing a minimum width for the value of zero in AmCharts column series by customizing the bullet labels

Here's an interesting example where I have arranged column series with bullet labels. However, you may notice that there are some 0 values present as well. My goal is to establish a minimum width for the series so that even if the value is small or 0, ...

Sorting Vue.js properties based on object keys

Currently, I am dealing with a complex object that contains multiple network interfaces. Each interface is represented by a key-value pair in the object: https://i.stack.imgur.com/klkhH.png My goal is to create a Vue.js computed property that filters thi ...

Understanding the Distinction Between Date and Datetime Fields in ASP.NET

Hey there, I'm working on an ASP.NET form using MVC3/Razor and I'm looking to customize the display of a date field that is currently a datetime field. In certain data columns, the time is important so I want both the date and time displayed, whi ...

Solutions for resolving the error "Unable to access property 'value1' because it is undefined"

constructor() { super(); this.state = { value1 : Math.floor(Math.random() * 100), value2 : Math.floor(Math.random() * 100), value3 : Math.floor(Math.random() * 100), proposedAnswer : Math.floor(Math.random() * 3) + this.state.value1 + t ...

Guide on adjusting the darkness of a MaterialUI Avatar component image and adding text to it

I'm currently working with the Avatar component from Material UI along with Tailwind CSS. I found that by simply adding the image URL to the src, it displays the avatar successfully. <Avatar alt="Cindy Baker" src="https://mui.com/sta ...

In order to properly execute the JavaScript code, it is essential to create a highly customized HTML layout from the ER

I am currently utilizing this resource to create a gallery of images on my Rails page. Here is the HTML code required to display the images: <a href="assets/gallery/ave.jpg" title="Ave" data-gallery> <img src="assets/gallery/ave_tb.jpg" alt="Av ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Error: Attempting to access 'title' property of undefined object leads to Uncaught TypeError

I am attempting to extract content from a Google Blogger Feed that can be found at this link. I am using JavaScript code from here. When inspecting the elements, I encountered a specific red warning message: Uncaught TypeError: Cannot read property ' ...

How can AngularJS handle uploading multipart form data along with a file?

Although I am new to angular.js, I have a solid understanding of the fundamentals. My goal is to upload both a file and some form data as multipart form data. I've learned that this is not a built-in feature of angular, but third-party libraries can ...

Tips for resolving issues with dynamically displaying state information based on a selected country

I'm currently working on a project that requires me to dynamically fetch the states of a specific country when a user selects the country of birth for their family members. To do this, I am utilizing AJAX. Due to limitations, I can only include detai ...

Error: The internal modules of node.js encountered an issue while loading causing an error to be thrown at

After installing Node.js (LTS version) from their website on my Windows system, I created a new directory named "mynode" and placed a text file inside it called "hellonode.js". Upon trying to run node hellonode.js in the command prompt after changing direc ...

Is Local Storage compatible with phonegap?

I am looking to integrate local storage into my phonegap application in order to store an array of data. Here is a snippet of my code: <div data-role="collapsibleset"> <div data-role="collapsible"> <h3>LOG ...

Showing JSON information on a web browser

Here is a snippet of JSON data that I am working with: {"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.36899999999999977262632455676794 ...

Guide on how to design a schema in Mongoose for uploading arrays of objects in MongoDB

[ const arrayOfObjectsSchema = new Schema({ array: [ { title: { type: String, required: true, }, desc: { type: String, required: true, }, img: { type: String, required: tru ...

Having trouble with the JQuery scrollTop animation? Getting the error message "Cannot read property 'top' of undefined"?

I am having trouble with my jquery animation scrollTop function. Whenever I click on <a>, it takes me to the anchor without any animation. Can someone please provide a solution for this issue? Upon running the webpage, I encountered an error message ...