Count of daily features in JavaScript

Suppose there is a json document structured as follows:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "time": 1438342780,
        "title": "Iran's foreign minister calls for world's nuclear weapons states to disarm",
        "author": "Julian Borger",
        "web_id": "world/2015/jul/31/iran-nuclear-weapons-states-disarm-israel"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -77.26526,
          38.90122
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "time": 1438300867,
        "title": "Big bangs over the white cliffs of Dover as unique 1915 artillery gun is fired again",
        "author": "Maev Kennedy",
        "web_id": "world/2015/jul/31/big-bangs-over-white-cliffs-dover-unique-1915-artillery-gun-fired-again"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          1.3,
          51.13333
        ]
      }
    }
  ]
}

If we need to extract the 'feature' array from the json and determine the total number of features for a specific date, we would aim for an output like this:

{
  "date": 7/31/2015,
  "number": 2
}

The current approach in handling the data involves utilizing D3.js to load the json file:

d3.json('path/to/json', function(json) {
    data = json;
});

As someone fairly new to JavaScript and D3, seeking guidance on how to achieve this task efficiently. Additional information can be provided upon request. Appreciate any assistance in advance!

Answer №1

This code snippet is tailored for your needs, as it generates an array of objects with specific properties.

const input = yourJSONObject;
const map = {};
const outputArray = [];

for (let index = 0; index < input.features.length; index++) {
 const reference = new Date(input.features[index].properties.time * 1000).toDateString();
 if (map[reference] === undefined) {
  map[reference] = outputArray.push({
    date: reference,
    number: 1
  }) - 1;
 } else {
    outputArray[map[reference]].number++;
 }
}

console.log(outputArray); // Example result: [ { date: 'Sat Jan 17 1970', number: 2 } ]

Answer №2

To successfully analyze your data, it is crucial to note that the time values are stored in Epoch time format. Therefore, you will need to convert them into readable dates by utilizing this method.

Once the conversion is complete, you can proceed to iterate through the features array and keep track of the occurrence count for each date.

var features = yourJSONObject.features;
var featuresByDate = {};

for (var i = 0, len = features.length; i < len; i++) {
    // retrieve the current feature's date
    var epochTime = features[0].properties.time;
    var date = new Date(0);
    date.setUTCSeconds(epochTime);

    // transform the date into '7/31/2015' format
    var dateStr = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();

    // check if the date has been counted before
    if (!featuresByDate.hasOwnProperty(dateStr)) {
        featuresByDate[dateStr] = 1; // first occurrence of the date
    } else {
        featuresByDate[dateStr]++; // increment counter for the date
    }
}

Answer №3

Two different functions are utilized in this code snippet. The first function is responsible for obtaining the accurate date based on the epoch time provided, while the second function iterates through the features to construct a temporary object. Subsequently, it further iterates through the object to generate an array containing date and number objects.

function retrieveDate(time) {
  var d = new Date(0);
  d.setUTCSeconds(time);
  return [d.getMonth() + 1, d.getDate(), d.getFullYear()].join('/');
}

function extractData(data) {
  var obj = data.features.reduce(function(prev, curr) {
    var date = retrieveDate(curr.properties.time);
    prev[date] = (prev[date] + 1) || 1;
    return prev;
  }, {});
  return Object.keys(obj).map(function (element) {
    return { date: element, number: obj[element] };
  });
}

extractData(data);

OUTPUT

[
  {
    "date": "7/31/2015",
    "number": 2
  }
]

DEMO

Answer №4

Although I am not familiar with D3, you can achieve this using pure JS:

var json = {
    "features": [{
        "type": "Feature",
        "properties": {
            "time": 1438342780,
            "title": "Iran's foreign minister calls for world's nuclear weapons states to disarm"
        }
    }, {
        "type": "Feature",
        "properties": {
            "time": 1438300867,
            "title": "Big bangs over the white cliffs of Dover as unique 1915 artillery gun is fired again"
        }
    }, {
        "type": "Feature same date",
        "properties": {
            "time": 1448300867,
            "title": "Big bangs over the white cliffs of Dover as unique 1915 artillery gun is fired again"
        }
    }]
}

var counts = {}

function secondsToDate(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toDateString();
}

json.features.reduce((counts, feature) => {
    var date = secondsToDate(feature.properties.time)
    if (counts[date]) {
        counts[date]++
    } else {
        counts[date] = 1
    }
    return counts
}, counts)

console.log(counts) // {'Fri Jul 31 2015': 2, 'Mon Nov 23 2015': 1}

The missing bit is parsing your timestamp into a date.

Now grouping on dates. Maybe now the downvoter can undo that!

I added an object with a replicated timestamp to highlight the count going up.

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

Search and extract JSON data in MySQL

Currently, I am inputting JSON objects into a MySQL Database and then executing queries on them. Within the database is a table structured as follows: subjects | ----------------------------------------------- ...

Leveraging the "dialogclose" event within jQuery Mobile

Is there a way to change an image once it is clicked and change back when the dialog it links to is closed? I found a potential solution on this site, but after modifying it for my needs, it doesn't seem to work. Can anyone help me figure out what I a ...

Assign a value to the Angular directive for the SharePoint People Picker

In my create form, I have successfully used a directive to capture and store values in SharePoint via REST. The directive I am using can be found at this link. Within my HTML, I am implementing the directive like this: <sp-people-picker name="CC" id=" ...

Switch between accordion items

Currently, I have a React Js accordion in which clicking on an item opens the panel. To close it, you need to click on another item. However, I am looking to enhance this functionality by allowing the active panel to be closed after clicking on the AccButt ...

"Use jquerytools to create a dynamic play/pause button functionality for scrollable content

Greetings! I am currently working on creating a slide using Jquerytools. Here are some helpful links for reference: To view the gallery demonstration, please visit: For information on autoscroll functionality, check out: If you'd like to see my cod ...

"Single-use: Ajax event executes only on the first attempt

Upon entering incorrect details and running it, an error message pops up. However, when entering the correct details and clicking run again, the sign in button changes to "Connecting..." as expected but nothing else happens. $(document).ready(function() ...

Playing audio from local blob data is not supported on mobile browsers

I'm trying to stream blob data in mp3 format, but I'm experiencing difficulties with mobile browsers. The code below works perfectly on PC browsers, but not on mobile: // Javascript var url = URL.createObjectURL(blob); audio = document.getEleme ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

When trying to export a JSON file from an Angular app, the URL is prefixed with 'unsafe' and the download fails with a network error message

Looking for guidance on exporting a JSON file from an angular app. Below is the code snippet I am using: app.js file: app.config(['$compileProvider', function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(htt ...

The properly grouped image failed to load

I have a React component designed to showcase an image, with Webpack handling the bundling process. It's important to mention that I am utilizing ReactJS.NET in this scenario. Even though the webpack bundle is successfully generated and the .jpg fil ...

Executing the command causes an error when res.download() is called, resulting in a request

I am currently working on developing an archive that includes various .txt files and then I intend to download this archive. Take a look at the code snippet below: async function archiveAndDownload(res) { const bashCommand = ... const archive = ... ...

get the value from an array by applying jq

Looking to craft a jq query that can iterate through the JSON data provided below and extract the value of FileSystemId when the Name is "efs-docker". If no matching records are found, the script should terminate. I initially tried using a foreach loop, bu ...

How can you include a multi-layered array within another multi-layered array using TypeScript?

If we want to extend a two-dimensional array without creating a new one, the following approach can be taken: let array:number[][] = [ [5, 6], ]; We also have two other two-dimensional arrays named a1 and a2: let a1:number[][] = [[1, 2], [3, 4]]; let ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

What are some methods to improve the performance of this jQuery-powered webpage?

I've developed a contact script that leverages jQuery for ajax requests and animations. However, the sluggish aspect arises when using a hashchange plugin to improve the functionality of the back button. Upon completing the animation for the 'f ...

Is there a way to personalize the chart tooltip in jqplot to fit my preferences?

I have a chart that displays data. I would like the x-axis labels to show in the format MM/DD, and in the tooltip, I want to display data in the format HH:y-axis. For example, in the chart below, I want the x-axis labels to be 'Oct 15','Oct ...

AngularJS - Refreshing Controller when Route Changes

Scenario app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.data = $routeParams; }]); app.config(['$routeProvider', function ($routeProvider) { ...

Symfony's DataTables is encountering an issue with the JSON response, showing

I have encountered an issue while trying to fetch data from a response within my template table (using DataTables). The error message I receive is as follows: DataTables warning: table id=example - Invalid JSON response. For more information about this ...

What is the best way to pass a single object from an array of objects to zingchart?

Imagine I have an array filled with objects structured like this: var sampleArray = [ {difference: "0.000", totalItems: 3}, {difference: "0.001", totalItems: 3}, {difference: "0.002", totalItems: 4}, {difference: "0.003", totalItems: 2}, {difference: "0. ...

Populate the existing SQL view with data from the Json table

Having an issue here! I need to transfer data from a JSON stored in a table with just one field directly to a view. However, I am aware that it is not possible to update or insert data into a view. Does anyone have any idea on how I can modify or configure ...