Personalized categorization of d3 information

My json data consists of timestamps like:

[{"Time":"2017-02-07 16:14:06"},
{"Time":"2017-02-07 16:58:49"},
{"Time":"2017-02-07 17:07:11"},
{"Time":"2017-02-07 18:13:19"},
{"Time":"2017-02-07 13:56:06"},
{"Time":"2017-02-07 19:07:57"},
{"Time":"2017-02-07 12:08:58"},
{"Time":"2017-02-07 01:41:00"},
{"Time":"2017-02-07 11:56:49"},
{"Time":"2017-02-07 02:45:29"},
{"Time":"2017-02-07 11:40:07"},
{"Time":"2017-02-07 04:15:45"},
]

To convert these into 24-hour values, I use the following d3.json function with a parsing mechanism:

var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;

d3.json("/wp-content/themes/jordan/js/data.json", function(d){

    d.forEach(function(d){
        d.Time = parseDate(d.Time).getHours();
        console.log(d.Time);
    });
});

After obtaining integer representations of hours, I am now looking to group these values into 4-hour increments using d3.nest(). For example, I want to group them as follows: 0 - 4, 4 - 8, 8 - 12, 12 - 16, 16 - 20, 20 - 24. How can I achieve this using d3.nest()?

Answer №1

If you create the periods array with the following values:

var periods = ['0 - 4', '4 - 8', '8 - 12', '12 - 16', '16 - 20', '20 - 24']

Then you can determine which period a specific hour belongs to using this code:

period[Math.floor(d/4)]

Complete code snippet:

var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse,
    periods = ['0 - 4', '4 - 8', '8 - 12', '12 - 16', '16 - 20', '20 - 24'];

d3.json("/wp-content/themes/jordan/js/data.json", function(data) {
    data = data.map(function(d) {
        return parseDate(d.Time).getHours();
    });

    data = d3.nest()
             .key(function(d) {
                 return periods[Math.floor(d/4)];
             })
             .entries(data);
});

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

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

Is there a way to extract the timestamp in JavaScript from a string that includes the name of the timezone database?

Given the string: "2022/05/01 03:10:00", I am seeking to create a Date object with Chile's UTC offset. The challenge lies in the fact that due to Daylight saving time (DST), the offset changes twice annually. How can I obtain that Date obj ...

Retrieving information from incoming JSON within a Java servlet

I have a client sending me a JSON file via HTTP PUT. Here is the content of the file: { "nomPers": "Testworking", "prenomPers": "WorkingTest", "loginPers": "Work", "pwdPers": "Ing", "active": true }, For my WebService framewo ...

React does not allow objects as child elements. Instead, render a collection of children by using an array

Encountering an error with this React class Error: Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead. Is there anything amiss here? I am passing the movies ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

Displaying column data in a popup modal using DataTables

I am facing an issue with displaying a long string from a column in my table in a popup modal. Upon clicking the button to launch the modal, instead of opening the modal, the page refreshes and nothing is logged to the console. Below is the HTML code for ...

Unforeseen execution issues arising from repeated Ajax calls with SetTimeout in JavaScript

I have a list of users displayed in an HTML table that is dynamically created on page load. Each row includes an inline button with onclick="functionName(userId)" that triggers the following actions: When clicked, a Bootstrap modal popup is shown and the ...

How can I create a JSON string that exactly matches the data source needed for a pie chart? Any tips

received JSON string: "{Date:'15/05/2015',y:'6'}, {Date:'01/08/2015',y:'6'}, {Date:'02/08/2015',y:'6'}, {Date:'08/08/2015',y:'72'}, {Date:'09/08/2015',y:&apo ...

Utilizing JSON data extraction technique to send it as props in Next.js application

I'm facing a dilemma at the moment: To populate the DataGrid component, I need to pass props As a result, I've employed getStaticProps to retrieve JSON data from an API and send it back as props. The catch is, I only require 3 attributes from ea ...

Transforming an array in JavaScript into a JSON object

I'm currently working on creating a loop in JavaScript or jQuery to generate a new JSON object from an array. The goal is to convert an input JavaScript array into a desired format for the output. Here's the input array: INPUT: [ { ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Tips for incorporating MIDI player for notes sequence using MIDI.js

Incorporating MIDI.js into my current project to play a sequence of MIDI notes. See below for the code snippet: for (var repeat = 0; repeat < melodyrepititions; repeat++) { for (var i = 0; i < composition.length; i++) ...

Acquire the value of ant-design Select dropdown upon hover

How can we detect the selected option in an ant-design dropdown when it is hovered? <Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value=& ...

Retrieve JSON data without keys in Python

I need assistance with extracting location data from a JSON API service. Here is my current progress: >>> import json >>> import urllib >>> from urllib import urlopen >>> url = urlopen('THE API URL').read() &g ...

Transmit JavaScript code from ASP.NET

Trying to transfer JavaScript code built using String Builder on the server-side (ASP.NET) to the HTML page's JavaScript. Here is my approach: Utilizing a Master Page and an ASPX page structured like this: <asp:Content ID="BodyContent" ContentPla ...

Combining and adding together numerous objects within an array using JavaScript

I'm looking to combine two objects into a single total object and calculate the percentage change between the two values. I'm encountering some difficulties while trying to implement this logic, especially since the data is dynamic and there coul ...

Mastering the use of swift protocols within model classes

JSON: "sittingFurniture":[ { "sittingObjectType": "chair", "fabric": "textile" }, { "sittingObjectType":"bed", "height": 70 }, ... ] Swift code: protocol Sitti ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

Exploring the hover functionality in GetOrgChart

Exploring mouse hover functionality in Getorgchart view. Looking to implement the mouse hover and mouse out events in Getorgchart view. Can I access the org chart element details during mouse hover/leave actions? ...

Encountered a 404 error while utilizing the Java - Angular web service

Encountering an error 404 in Firebug when attempting to send an object from Angular to a Java controller using JSON. While the backend in Java is able to receive the message, Angular is unable to find the specified path. Consequently, there is an issue wit ...