What is the best approach to filter data in D3 by multiple variables within JSON data?

Seeking guidance with D3.js for my new project. I have JSON data containing course titles, attendance records, and last attendance dates. How can I filter or manipulate this data to calculate the mean attendance for each individual course title within the past 30 days?

{
"Course_title": "Adv Mech Eng",
"Attendance_record": 0.89,
"Last_attendance": "2018-10-19 09:00:00.000",
},
{
 "Course_title": "Comp Sci",
 "Attendance_record": 0.50,
 "Last_attendance": "2018-10-19 15:59:59.999"
 }

I attempted using d3.nest() and d3.mean() functions, but struggling with incorporating the date element into the code for a d3 chart. Any assistance from experienced D3 users would be greatly appreciated!

Answer №1

If you're looking to extract a date parameter, consider utilizing d3.utcParse function. Another useful tool is the filter option for sorting courses based on dates.

To retrieve the date from 30 days ago, refer to this resource shared in an SO post: how-to-get-30-days-prior-to-current-date

Check out the following example:

d3.json('attendance_data.json', function(data) {

  //Current date and date 30 days ago
  var currentDate = new Date()
  var thirtyDaysAgo = new Date(new Date().setDate(currentDate.getDate()-30))

  // Creating parser for "Last_attendance"
  var parseDate = d3.utcParse("%Y-%m-%d %H:%M:%S.%L")

  // Filter data for courses occurring in the last 30 days
  var filteredCourses = data.filter(function(d){
    return parseDate(d.Last_attendance) > new Date(thirtyDaysAgo);
  })

  var avgData = d3.nest()
    .key(function (d) {
      return d.Course_title; // Grouping by course title
    })
    .rollup(function (courses) {
      return d3.mean(courses, function (d) {
        return d.Attendance_record; // Calculating mean attendance
      });
    })
    .entries(filteredCourses);

 
  console.log(JSON.stringify(avgData));

})
<script src="https://d3js.org/d3.v4.min.js"></script>

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

Assistance is needed in integrating pinch zoom into the css3d_youtube demo in three.js. The trackball controls are causing issues with the

I am facing the challenge of convincing my boss to implement three.js for a CSS3D interface integrated with video providers like YouTube. One of the key requirements is that it must work seamlessly on mobile devices, so I have chosen to demonstrate it on a ...

Exploring the Interplay of JSON Objects in SQL Server and C#

After executing the following SQL Server query, I successfully created a JSON object: SELECT Attribute 1, Attribute 2, Attribute 3,... AS Identifier FROM Table_1 tbl1_obj INNER JOIN Table_2 tbl2_obj ON tbl2_obj.Id = tbl1_obj.Id FOR JSON AU ...

Having trouble getting rid of the border-bottom?

I have been attempting to customize the appearance of the React Material UI tabs in order to achieve a design similar to this: https://i.stack.imgur.com/tBS1K.png My efforts involved setting box-shadow for the selected tab and removing the bottom border. ...

The returned state from setState(prev) seems to be in the opposite order when referencing another useState variable within a useEffect

As part of my interactive chat simulation project, I have implemented a feature where users can click on a button named obj4 to start their chat session. Initially, everything functions smoothly, displaying messages 1-4 in the correct order. However, when ...

Tips for sending formData (file upload) via jQuery ajax with MVC model

My Web Development Challenge : //IMAGE UPLOAD var formData = new FormData(); var totalImages = document.getElementById("ImageUpload").files.length; for (var x = 0; x < totalImages; x++) { ...

Error thrown by Jest: TypeError - req.headers.get function is not defined

I have a function that is used to find the header in the request object: export async function authorizeAccess(req: Request): Promise<Response | {}> { const access = req.headers.get('Access') if(!access) return Response.json('N ...

Load remote JSON data into WordPress Advanced Custom Fields through the backend

I have a custom post type called "Products" and I am using the ACF (Advanced Custom Fields) plugin with this post type. The fields group in ACF includes: - One field named 'Product Description' as a text area - Three text fields named 'Feat ...

Unveiling the significance behind the utilization of the.reduce() function in conjunction with Object.assign()

After consulting the method/object definitions on MDN, I am attempting to create a simplified step-by-step explanation of how the script below (referenced from a previous post) is functioning. This will not only aid in my understanding but also help me ada ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Analyze the value of key.name against a string within a JSON reply

Below is the JSON data I am working with: { "value": [ { "id": "/subscriptions/5a9c0639-4045-4c23-8418-fc091e8d1e31/resourceGroups/citrix-xd-0ec69105-c451-4676-8723-97932bf4d94a-ayjzs", "name": "citrix-xd-0ec69105-c451- ...

Issue encountered while attempting to deactivate certain foundation CSS and JavaScript files

I am attempting to deactivate certain CSS files in the foundation framework, as they are unnecessary for my project. After installing foundation via a gem, I followed Ryan Bates' recommendation to modify the foundation_and_overrides.scss file by repl ...

What is the best way to incorporate the "child_process" node module into an Angular application?

Trying to execute a shell script in my Angular application has been quite the challenge. I came across the "child process" node library that might be able to help me with this task. However, every attempt to import the library led me to the error message: ...

Looking to showcase both input and output on a single PHP page?

I am working with a table that fetches rows from a database. I need to display the output of each row next to the table itself. The data for the output is also retrieved from the database. For example, when a user clicks on a particular row, I want to sho ...

The changes to the grid options do not reflect immediately on the UI Grid interface

I am currently working on a project using the UI Grid module in AngularJS. I want to include row filtering as an option, but since not all users require it and the filter boxes take up a lot of space, I decided to disable filtering by default and add a but ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Concealing Angular Flexslider until it is entirely loaded

I'm having trouble getting my angular flexslider to display images smoothly. Currently, the images take a moment to load and it doesn't look great. I'd like them to fade in once everything is fully loaded. How can I achieve this? I've t ...

formik does not support using the "new Date" function as an initial value

I have been trying to set the initial value of a date in my component like this, but when it renders I am encountering an error. const formik = useFormik ({ initialValues: { dob: new Date () } }) During this process, I'm facing the follow ...

The AngularJS error message [$rootScope:infdig] is triggered when the number of $digest() iterations exceeds 10 due to a window

It's evident that changing window.location.href/reload to $location.path() resolves the issue. However, using $location.path breaks the app in IE but works in Chrome with window. The purpose behind this is to update a site when a user logs in or out, ...

JS, Async (library), Express. Issue with response() function not functioning properly within an async context

After completing some asynchronous operations using Async.waterfall([], cb), I attempted to call res(). Unfortunately, it appears that the req/res objects are not accessible in that scope. Instead, I have to call them from my callback function cb. functio ...

The type unknown[] cannot be assigned to type React.ReactNode

import * as React from 'react'; import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material'; import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined'; import NotificationsNoneOutl ...