Looking for a specific portion of a key-value pair

Currently, I am working on developing an application that will showcase parking tickets issued in New York City. The API that I am utilizing can be found at this link. My goal is to generate a graph illustrating the number of tickets handed out per month. Within the dataset, there exists a column named "issue_date", which contains the year, month, and additional numbers that are unfamiliar to me. Is it feasible to extract only the year and month portion from this column rather than the entire string? For instance, if I wish to view tickets issued in January, would it be possible for me to search for entries like 2017-01 without considering the rest of the data and causing errors in my code? Thank you for your assistance!

I wanted to mention that I am currently a first-year college student with limited programming knowledge. Apologies for any inconvenience caused by my lack of expertise.

Answer №1

To extract the first 7 characters from the date, you simply need to grab them.

Below is a code snippet that demonstrates how to tally the number of entries per month and store this information in an array:

fetch("https://data.cityofnewyork.us/resource/ati4-9cgt.json")
   .then(resp => resp.json()).then(data => {
        const byMonth = Object.entries(data.reduce( (acc, row) => {
            const month = row.issue_date.slice(0,7); // <--- extracting YYYY-MM
            acc[month] = acc[month] || 0;
            acc[month]++; // <--- incrementing count
            return acc;
        }, {})).sort((a, b) => a[0].localeCompare(b[0])); // <--- sorting months
        console.log(byMonth); // <--- displaying [[month, count], [month, count], ...] 
    });

Answer №2

Use regular expressions to match the issue date format, for example: /^2017-01/

If you have an array of objects, you can filter them based on the issue date by using:

onlyOnJanuary2017 = wholeArray.filter(object => object.issue_date.match(/^2017-01/));
like shown here: https://jsfiddle.net/twpq6nvd/

Additionally, if you want to group them by month and year, you can try this approach:

var result = arr.reduce((accumulator, item) => {
  const date = new Date(item.issue_date)
  var key = `${date.getFullYear()}-${date.getMonth()}`
  accumulator[key] = accumulator[key] || [];
  accumulator[key].push(item);
  return accumulator;
}, {})

https://jsfiddle.net/d3qa96bg/1/

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

How can I access an array option that combines both global and target-specific specifications within a grunt plugin?

Currently, I am in the process of creating a grunt plugin that includes options which can consist of arrays of values. These values are specifically file paths (distinct from the files listed in the task's own 'files' property). The setup fo ...

Implementing additional input with Jquery causes tooltips to malfunction

I am developing a form that allows users to add as many rows as needed. Each input is being treated as an array for easy data storage in the database, which is a new concept for me. $(document).ready(function() { var maxField = 10; //Limitati ...

Heroku refreshes my JSON document

My node.js app relies on a basic JSON file as the model. To keep things simple since it's only an MVP with minimal data storage requirements, I opted not to set up and configure a MongoDB database. Instead, I just read from and write to a JSON file lo ...

What could be causing this addEventListener to fail when I am assigning elements to a class?

I've encountered an issue with my code where I have two text inputs and two date inputs. I tried to select all of them using QuerySelectorAll with a class, added a click listener that should change the textContent of a div element to "", but it's ...

Watching a Computed Value in EmberJS

What causes the discrepancy between the two sets of code? Utilizing computed: computed: Ember.computed('selected', function() { console.log('computed'); return this.get('selected'); }), observer1: Ember.observer(&ap ...

Verification - enter a unique key for each ajax call

As I develop a new app, I am aiming to separate the HTML/JS layer from the PHP layer in order to prepare for a potential phonegap version in the future. One major concern I have is regarding authentication. Since I won't be able to rely on session va ...

Is there a way to implement a RESTful persistence solution with backbone.js using PHP?

Let me start by admitting that programming is not my strong suit. I'm aware that achieving what I want could probably be done with just a few lines of code in node.js or Rails, but PHP is what I have to work with. With that said, I am on the lookout ...

The Checkbox generated by Javascript is failing to properly close the tag

When I generate a checkbox in this manner and insert it into my table's [TD] tag: let checkbox = document.createElement('input'); checkbox.type = 'checkbox'; td.appendChild(checkbox); It yields: <tr> <td> ...

The child division was not dynamically included

My HTML code currently looks like this: <div class="horizontal-double-large pink" data-title="health" data-legend-one="medical" data-legend-two="natural"> <div class="horizontal-double-element" data-name="India" data-one="40" data- ...

Dynamic form population with dropdown selection using Ajax - Coldfusion continuation

Following some valuable feedback from my previous inquiry, I have made progress: Refer to the original post - Coldfusion Populate form with dropdown selection using ajax Currently, I have successfully sent a request to my CFC with a remote function, but I ...

Exploring the functionality of jQuery by incorporating a variable into the selector

I attempted to modify the src attribute of an image file using a variable, but it did not actually change. Can anyone pinpoint where I went wrong in using the variable? jquery var p2begen = "416"; $("[id=i'" + p2begen + "']").attr("src", "check ...

What is the best approach to perform a search in mongoose based on specific query parameters?

I have a form that allows users to search for transactions by specifying the buyer name, item name, or both. This means I can receive any of these queries: localhost:8000/allPayments/?i=pasta localhost:8000/allPayments/?b=Youssef localhost:8000/ ...

Minimize API Requests in Your AngularJS Application

Currently in the process of developing a straightforward web application that interacts with an API service. One issue I've encountered is the API call limit, which hinders the functionality if exceeded. How can I optimize my API calls to stay within ...

Use Object.assign to swap out the current state with a new

Why does the React component with state { key: bool } not omit the existing state key from the new state when a different option is clicked? Link to the code var SampleComponent = React.createClass({ getInitialState: function() { return {}; }, ...

After the rendering of the HTML, the value of the jQuery input does not change

Here we have a function that loads HTML onto the form class in a file. The quest[q] locates the appropriate HTML template to load from an array of templates. The HTML being loaded contains an input with an id of "p". I am attempting to set the value of th ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

How to implement and utilize a history-object interface in React with Typescript?

Can you help me with setting up an interface for a history object in my component? Currently, it is typed as any and I want to type it appropriately. Object: https://i.sstatic.net/Sru8R.png Here's the code snippet: import React, { useState } from &a ...

Utilizing Laravel 8 for seamless file uploads with AJAX on onchange event

I'm trying to implement a feature in my Laravel 8 application where users can upload multiple files using the onchange event. Is it possible to achieve this functionality with just the onchange event? Below is the HTML form I currently have. Any assis ...

The function is coming back with a value of undefined

I need some assistance with a function I have below. This function is meant to download files one by one and move them to a directory called templates. At the end, it should return the length of the directory. However, it seems to be returning an undefined ...

Saving Backbone.js Collection as Text File on HDD & Re-importing Data

After experimenting with Backbone.js for a while, I've relied on localStorage to store most of my app data. However, I now want to explore the possibility of exporting my collection to plain text for easy backup purposes. Essentially, I envision a fea ...