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

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

Having trouble with @here/maps-api-for-javascript in Next.js - it's not functioning

Can anyone help me understand why @here/maps-api-for-javascript is not functioning properly in my Next.js application and producing the following error message: import H from "@here/maps-api-for-javascript"; export default H; ^^^^^^ SyntaxErr ...

Skip ahead button for fast forwarding html5 video

One of the features in my video player is a skip button that allows users to jump to the end of the video. Below is the HTML code for the video player: <video id="video1" style="height: 100%" class="video-js vjs-default-skin" controls muted autoplay=" ...

ReactJS Material-UI Tooltip and Popper overlapping issue

How can I make the MUI tooltip appear beneath the MUI Popper, with the popper overlapping the tooltip? Is there a way to modify the z-index for only a specific portion of the elements without affecting the global styles when using external CSS? Here is a ...

The Google Visualization chart fails to display properly once CSS is applied

Struggling with a graph display issue here. It's quite perplexing as it works fine on older laptops and Safari, but not on Chrome or older versions of Firefox. Works like a charm on my old laptop and Safari, but fails on Chrome and Firefox (haven&apo ...

What is the best method to transfer an array as a parameter from an Ipython notebook to an HTML file that includes specific javascript functions?

I have a unique HTML file named "file.html" that includes a distinctive JavaScript function described below: The Unique file.html <html> <head> </head> <script> function customFunction() { perform an action using ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

``Using backticks to denote HTML syntax - Leveraging Google Charts to create

Has anyone found a way to incorporate HTML in ticks within a Google chart? I am attempting to insert a weather icon from This is my current attempt: const dailyData = new google.visualization.DataTable(); dailyData.addColumn('timeofday' ...

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read. For reference, something similar can be seen on this site. I have created my custom progress bar and coded it on fiddle, whe ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

The system is currently unable to find the specified element

I am facing an issue trying to locate a button that is defined under a specific class using XPATH. The error message "Unable to locate element" keeps popping up. Here are the details of the class: <div class="aui-button-holder inputBtn" id="aui_3_4_0_1 ...

Issues with AJAX requests failing to fire with the latest version of jQuery

A small script I have checks the availability of a username in the database, displaying "taken" if it's already taken and "available" if it's not. The code below works perfectly with jQuery v1.7.2. However, I need to update it for jQuery v3.2.1. ...

Selecting a color in Vuetify's color picker triggers the @

I have incorporated the Vuetify color picker into my project for changing the background and text colors of elements. Currently, I am storing the hex color values in Firestore by using the @input="updateColor" attribute on the v-color-picker to t ...

How can I dynamically update the status displayed in a DIV tag using PHP code?

I'm working on a web page where I am downloading data one by one in a continuous loop. Once each download is complete, I need to update the status displayed in a DIV tag on the webpage. The server connection and data download are handled by PHP code, ...

excess white space appears in the mobile version

I recently completed a website using both materializecss and bootstrap platforms. While I know this may not be the best practice, it worked for my needs. However, I am facing an issue with the mobile view. When I reduce the viewport size, a margin appear ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...

Steps for converting TypeScript code to JavaScript using jQuery, without the need for extra libraries or frameworks like NPM

My single-page dashboard is quite basic, as it just displays weather updates and subway alerts. I usually refresh it on my local machine, and the structure looked like this: project/ index.html jquery-3.3.1.min.js script.js I decided to switch it t ...

What advantages does the use of $(e).attr(name,value) offer compared to using e.setAttribute(name,value)?

Scenario: The variable "e" represents an element of type "HtmlElement" and not a "css selector" I am referring to any attribute, not just the standard allowed ones like "atom-type" or "data-atom-type". Regardless of the attribute name, will it function wi ...

Can you create a dynamic visual display using HTML5 Canvas to draw lines in a circular pattern that react

I have successfully implemented drawing lines around a circle using the AudioContext API. However, I am facing an issue with the lineTo function, as the line only grows and does not shrink. My inspiration for this project comes from the audio visualizer fo ...