Consolidate nested object in D3

After removing duplicate rows from my dataset using a d3.nest() function, I now have unique entries in my JSON array. My goal is to calculate the mean 'cycle time' for each date. The desired output should resemble:

[
  {
    "key": "2012-03",
    "values": [
      {
        "mean": 16,
      }
    ]
  },
  {
    "key": "2012-06",
    "values": [
      {
        "mean": 10,
      }
    ]
  },
  {
    "key": "2012-07",
    "values": [
      {
        "mean": 8,
      }
    ]
  }
]

I've attempted to follow online examples but it seems like I might be missing something obvious. Can someone please assist?

var summaryTable = [
  {
    "key": "2012-03",
    "values": [
      {
        "key": "AAA-1",
        "value": {
          "cycletime": 14
        }
      },
      {
        "key": "AAA-2",
        "value": {
          "cycletime": 18
        }
      }
    ]
  },
  {
    "key": "2012-06",
    "values": [
      {
        "key": "AAA-3",
        "value": {
          "cycletime": 8
        }
      },
      {
        "key": "AAA-4",
        "value": {
          "cycletime": 12
        }
      }
    ]
  },
  {
    "key": "2012-07",
    "values": [
      {
        "key": "AAA-5",
        "value": {
          "cycletime": 15
        }
      },
      {
        "key": "AAA-5",
        "value": {
          "cycletime": 1
        }
      },
      {
        "key": "AAA-6",
        "value": {
          "cycletime": 8
        }
      }
    ]
  }
]

var d3Table = d3.nest()
    .key(function(d) { return d['key']; })
    .rollup(function(d) { 
        return {
                "medianCycleTime": d3.mean(d, d3.values(d['values']['value'])),
        };
    })
    .entries(summaryTable);

Answer №1

Upon a thorough examination of your data utilizing the d3.nest method, I have identified the appropriate function to utilize within the rollup.

It is crucial to note that the argument 'd' in the rollup function represents an array containing all objects with the specified key. It is imperative to index this array first; otherwise, you may inadvertently trigger the values() method from the Array class.

var d3Table = d3.nest()
    .key(function(d) { return d['key']; })
    .rollup(function(d) {
        return { 
            "medianCycleTime": d3.mean(d[0]['values'], d => d.value.cycletime ),
        };
    })
    .entries(summaryTable);

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

Creating an instance without assigning a value to a variable in the constructor declaration

I am interested in developing a Node REST API using Typescript and have started by creating a basic class to manage the Express application. import express from 'express'; import { Server } from 'http'; import { injectable } from &apos ...

Methods for transferring checkbox values from JavaScript/view to controller in MVC

Currently, I am developing a form that allows users to select up to 11 football players from a list using checkboxes. The players are categorized and named by their playing positions. @if(item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x ...

What could be causing my item-list to malfunction in Vue.js?

I recently attempted to develop my own Vue.js application by following the provided documentation. Unfortunately, I encountered an error that has proven difficult to resolve. Despite my efforts to recreate the app as instructed, the list does not show an ...

Unable to fetch all data from the Json file

I have been retrieving JSON data from and then displaying the titles in a ListView. The code seems to be functioning correctly, but I am facing a challenge where some titles are getting skipped in my ListView and one particular title is being repeated. I ...

angular.js causing json data not being interpreted correctly as rows

Struggling with setting up an angular.js page to display data fetched through a http get request from a node.js server. Encountering issues with how angular is parsing the json data. Below is the index.html code snippet: <!DOCTYPE html> <html > ...

Creating a custom directive to mimic the behavior of ng-if

Hey there! I've got this cool directive that lets you conveniently hide or show elements: <div cdt-visible-to="Admin,Moderator">...</div> By using this directive, our HTML code becomes more declarative. Here's a snippet of what the ...

Implement a hover animation for the "sign up" button using React

How can I add an on hover animation to the "sign up" button? I've been looking everywhere for a solution but haven't found anything yet. <div onClick={() => toggleRegister("login")}>Sign In</div> ...

Key-Value Pairs in a Multidimensional Array using JavaScript

After making an AJAX request to a JSON, I receive the following code as a response: { total: "1", items: [ { id: 43, title: "ThisIsTheTitle", promoted: false, sticky: false, weight: 10, created: { timest ...

What is the best way to update specific values in a react multiselect component?

Within my modal, I have a form where I can edit my model. One of the fields in this form is a multi-select tag field called "tags", which is an array of objects consisting of labels and values as illustrated below. To populate this tag field, I have a dum ...

Explorer is malfunctioning and not functioning properly when trying to replace text using

I am currently using a JavaScript replace function to update text associated with two radio buttons on a predefined form. Here is the code snippet for the script: document.body.innerHTML=document.body.innerHTML.replace("Payment by <b>Moneybookers&l ...

What is the best way to modify a function so that it targets the element that called it?

I utilized the following Bootstrap 4 code to implement a functionality where clicking on a video would play/pause it, and simultaneously toggle a speaker image located below the video. I am looking for a way to refactor this function so that it only impac ...

Update Calendar Information Without Reloading the Entire Page

Is there a way to automatically refresh a div that includes a FullCalendar Calendar? I'm looking to refresh the div every 30 seconds to check for new data from the database without having to modify the ViewModel or reloading the page. index.html &l ...

Using Firebase Firestore to fetch an array field from a particular document and then leveraging those array values for mapping other documents

In my database, I have user and group collections. Each document in the user collection corresponds to a user UID and contains an array field called "userGroups" which lists the groups that user belongs to, with each group being identified by the group&apo ...

Utilizing Metalness with the MTLLoader in three.js

Lately, I've been utilizing MTLLoader to load my obj meshes in Threejs. Although it does the job by loading the correct textures, the material appears too dull for my liking. My expectation: https://i.sstatic.net/Z2T9d.png What I am currently seei ...

The functionality of Event Delegation stops working following an ajax request

I am currently working on a project that involves managing a table of elements. Whenever a row is clicked, I load the details into another div, make edits, and then reload the list if needed (for example, if something has been deleted or if the list needs ...

Avoid using the AJAX function if an identical request is already in progress

I have set up an AJAX request within a JavaScript function. By using the setInterval method, this AJAX function runs every 5000 milliseconds. I am curious if there is a way to determine if the previous AJAX call is still in progress to prevent multiple si ...

Creating a pop-up effect for a div in the center of a table cell using HTML and CSS

I am currently working with Angular and facing a challenge where I need to display a div like a popup in a table cell when clicked. Despite having the click event logic in place, I am unsure of how to achieve this without using external libraries such as B ...

Having difficulty setting up multiple buttons to share the same function in jQuery using HTML

After clicking a button, my code dynamically adds content to a div and inserts buttons with names like "teamReq_"+index+"_AddYear" into the document (where index is a number retrieved from a hidden input field). If these buttons are spammed, multiple divs ...

Manage and modify Firestore data and Firebase storage in an asynchronous manner

I've implemented a crud system for data storage that includes images. This system consists of fields for name, type, qty, description, and url. The url field is used to store the URL of an image that has previously been uploaded. Below is the code fo ...

Enclose the final portion of the content within a span element as an option

I could use some assistance. Currently, I have a variety of products in an online store with different options such as size and color. To demonstrate, I created a sample on this fiddle: https://jsfiddle.net/04wbfL28/2/ Here is the HTML snippet: < ...