Finding the average JSON value using d3.js

Here is the structure of a JSON file I am working with:

[
 {"id":1,"sex":"Female","programming":5, "project":7}, 
 {"id":2,"sex":"Male","programming":8, "project":4}, 
 {"id":3,"sex":"Female","programming":5, "project":6}, 
 {"id":4,"sex":"Male","programming":4, "project":7} 
]

To find the mean value of 'programming' using D3 js, you can calculate it like this:

function calculateMean(value) {
    return d3.mean(data, function(d) {return d[value] })
}

var overallProgrammingMean = calculateMean('programming');

Now, if you want separate means for 'programming' based on sex (female and male), you can achieve that by grouping the data. Here's how you can do it:

Answer №1

// To simplify the process, consider utilizing the d3.nest function. Here's an example to get you started:
var nest = d3.nest()
  .key(function(d) { return d.gender; })
  .sortKeys(d3.ascending)
  .rollup(function(d) {
    return {
      averageValue: d3.mean(d, function(g) { return g[value]; })
    };
  })
  .map(data);

// You may also need to convert it back into entries. I found that using map first and then extracting to entries worked for me.
// Still getting accustomed to d3 though!
var formattedData = d3.entries(nest);

Answer №2

If you're looking to filter out a new array containing only certain genders, you can achieve this by creating a new array specifically for Females or Males and then applying a function on the filtered array. Using jquery.map() makes it easy to create the new array.

For a visual example, check out THIS LINK.

var data = [
  {"id":1,"sex":"Female","programming":5, "project":7}, 
  {"id":2,"sex":"Male","programming":8, "project":4}, 
  {"id":3,"sex":"Female","programming":5, "project":6}, 
  {"id":4,"sex":"Male","programming":4, "project":7} 
];

var newArray = $.map(obj,function(elem){
  return elem.sex === 'Female'? elem :null;
});

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

Having trouble with the autocomplete feature on your textbox in CodeIgniter?

controller: Welcome.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { function __construct() { parent :: __construct(); $this->load->helper ...

Struggling to parse JSON data in Node.js using Express that was produced with JSONUtility in Unity

This is an example of a PUT request I'm using in Unity: UnityWebRequest request = UnityWebRequest.Put(baseUrl + "miniGame1s/", JsonUtility.ToJson(cardsToSend)); The object being sent, "cardsToSend", is based on the following class structure: [Seria ...

Navigation bar in reactjs remains visible even after clicking on an icon button, causing a temporary issue with

I'm facing an issue with my navigation bar created using material-ui. I have an onClick function set up so that when the user clicks the icon button, the navigation redirects to a new page and then should close. However, no matter what I try, the navi ...

`The console is displaying incorrect results when returning a JSON object`

Need to extract the full address as well as the lat and long values from the provided JSON data. var place = { "address_components": [{ "long_name": "17", "short_name": "17", "types": [ "street_number" ] }, ... ...

Move a div by dragging and dropping it without creating duplicates

I'm in need of some assistance. It seems like a simple task, but I'm having trouble finding a solution. I've managed to create draggable elements that work smoothly without any issues. The drag and drop functionality is working perfectly. ...

Is it possible to nest a React component within a state?

Is it permissible to use any of the three options below, but I can't find recent official information regarding this? constructor(props) { this.state = { item: <SomeItem />, item1: () => <SomeItem />, item2: Some ...

Having trouble parsing a JSON string that contains backslashes

Within my database, I have a string (character varying) that looks like this: [{"MountPoint":"C:\","FreeSpace":"18 GB","TotalCapacity":"39 GB","TotalBytes":42580570112,"FreeByt ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

How can I pull the account creation date stored in MongoDB and display it using Handlebars?

Currently in my development, I am utilizing MongoDB, NodeJS, and Handlebars. My challenge is to convert the user.id into a timestamp and then display this timestamp on my HTML page. At present, I can display the user.id by using {{ user.id }} in my code, ...

You must pass a string, Buffer, ArrayBuffer, or Array as the first argument when using Uint8Array.slice(). A number was received instead

Here is my implementation of the ByteArray class, which extends the Uint8Array class. export class ByteArray extends Uint8Array { ... private _encoded: string; ... constructor(_encoded: string) { super(Buffer.from(_encoded, " ...

Checking for the Existence of a Database Table in HTML5 Local Storage

Upon each visit to my page, I automatically generate a few local database tables if they do not already exist. Subsequently, I retrieve records from the Actual Database and insert them into these newly created local tables. I am wondering if there is a me ...

Adding and removing form fields in a table dynamically using AngularJS

I need to dynamically add multiple form fields when a button is pressed, and I want all the fields to be displayed in a table format (each field should have its own space in a <td>field</td> structure). Currently, I am facing an issue where if ...

What might be the reason behind a persistent JSON request for a fresh session?

After deploying a Rails 3.0.3 app, we encountered the following error: Started GET "/session/new" for 74.222.223.113 at Fri Feb 25 16:22:30 -0800 2011 Processing by SessionsController#new as JSON Completed in 25ms ** [Hoptoad] Success: Net::HTTPOK ** ...

Calculating the time gap between two consecutive "keyup" occurrences

I am in need of creating a basic point of sale system using Javascript. I have a barcode scanner that functions like a keyboard. My goal is to automatically identify when the input is coming from the barcode scanner and then generate a report with the sc ...

"Receiving EOF error while attempting to send JSON data to local Go backend with VueJS

I'm currently in the process of establishing a login system with VueJS for the frontend and Go for the backend. However, I've hit a roadblock when it comes to sending the username and password in JSON format to the backend. My current approach i ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

What could be causing the divs to overlap? Without the use of floats or absolute positioning,

When resizing vertically on mobile, my date-time-container is overlapping the upper elements welcome and weather. Despite setting them as block level elements, adding clear: both, and not using absolute positioning or floats, the overlap issue persists. An ...

I have successfully retrieved all blog API data, but now I need to specifically fetch a single blog post

import React, { useState } from "react"; import "./Blogs.css"; import "bootstrap"; import "bootstrap/dist/css/bootstrap.css"; import "bootstrap/dist/js/bootstrap.bundle"; function SinglePost() { const [d ...

Is there a way to execute a callback function once the page has finished loading through AJAX in

I'm in need of a way to attach new events and execute certain functions on a webpage that loads dynamically. Unfortunately, the resources I've found so far are outdated or lack necessary details (even the jqm docs). My current setup involves jQue ...

Showing information in a modal dialog in an Angular 4 application

As an Angular 4 developer, I am working on an application where I need to display data in a dialog. To achieve this, I am using @Output to pass data from the child component to the parent component. In the parent component, my code looks like this: expor ...