Discover the Power of Grouping by Distinct Names in D3

Data

newdata = [
   {'Name':'Andrew', 'Country':'US', 'Start date':'2012-7-2','Total':'30days'
}, {'Name':'Kat', 'Country':'US', 'Start date':'2012-2-2','Total':'24days'
}, {'Name':'Barry', 'Country':'France', 'Start date':'2012-12-2','Total':'22days'
}, {'Name':'Ash', 'Country':'US', 'Start date':'2015-2-2','Total':'20days'
}, {'Name':'Lucy', 'Country':'UK', 'Start date':'2016-2-2','Total':'35days'
}, {'Name':'Gerry', 'Country':'US', 'Start date':'2016-2-2','Total':'40days'
}, {'Name':'Alex', 'Country':'France', 'Start date':'2016-2-2','Total':'28days'
}, {'Name':'Morgan', 'Country':'UK', 'Start date':'2012-6-2','Total':'24days'
}];

I desire to form groups for each unique 'Country' value (3 in total) and then assign the corresponding 'Name' values to each group.

My inquiry is how can I extract the distinct 'Name' values for each 'Country' to create the groups?

I managed to create the 3 groups using d3.map() while binding the data, but this removed the other values.

https://jsfiddle.net/hellococomo/3d1asL4d/2/

Code

var canvas = d3.select('#chart')
  .append('svg')
  .attr('width', 350)
  .attr('height', 600)
  .append('g')
  .attr('transform', 'translate(0,20)')

var country = canvas
  .selectAll(".country")
  .data(newdata)

var countryEnter = country
  .enter().append("g")
  .attr('class', 'country')

countryEnter
  .append("text")
  .attr('class', 'name')

country.select('.name')
  .text(function(d, i) {
    return d.Country;
  })
  .attr('y', function(d, i) {
    return i * 30;
  });

UPDATE

Nesting worked successfully. I utilized d3.nest() as suggested by Cyril to generate keys from 'Country'. Additionally, I opted to use div and p elements instead of svg:g for this implementation.

New working code

var nested_data = d3.nest()
  .key(function(d) { return d.Country; })
  .entries(newdata);
   console.log(nested_data)

var canvas = d3.select('#chart')
  .attr('width', 350)
  .attr('height', 600)
  .attr('transform', 'translate(0,20)')

var country = canvas
  .selectAll(".country")
  .data(nested_data)

var countryEnter = country
  .enter().append('div')
  .attr('class', 'country')

countryEnter
  .append("p")
  .attr('class', 'label')
  .style('font-weight', 'bold')
  .text(function(d, i) {
    return d.key;
  })

countryEnter.selectAll('.name')
    .data(function(d) {
      return d.values;
    })
    .enter().append('p')
    .attr('class', 'name')
     .text(function(d) {
      return d.Name;
    })

Answer №1

If you want to organize your data, consider using the nest function

var grouped_data = d3.nest()
.key(function(d) { return d.Country; })
.entries(newdata);
console.log(grouped_data)

I hope this explanation is useful!

For more information, check out this resource http://bl.ocks.org/phoebebright/raw/3176159/

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

Tips on creating a search feature with JavaScript and AJAX

I'm currently facing an issue with my search functionality. I have successfully loaded data from a JSON file, but the search feature is not working as expected. I've reviewed my code multiple times and can't identify any mistakes. I believe ...

Ensure that a synchronous action is performed prior to each Backbone HTTP request

For each authenticated request (GET, POST, etc) in my Backbone/Marionette application, it is necessary to include an accessToken. The accessToken and expireDate are stored in the localStorage. To verify if the accessToken has expired, I utilize the metho ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

Is there a way to identify the source of a div's scrolling behavior?

While working on a complex web page that involves multiple JQuery Dialogs and other widgets, I encountered a frustrating issue. Some of the dialogs contain divs with scrolling abilities (using overflow-y with a fixed height). Whenever I click on one dialog ...

Navigating a local and server environment with relative paths in a web server's multiple sites

My ASP.NET website is published to a web server with multiple sites, such as www.example.com/SiteA or www.example.com/SiteB. Before publishing, I test the site locally at localhost:12345. When referencing an image path like /Images/exampleImage.gif, it wo ...

Creating a dynamic JSON object and retrieving the response in a JSP for data-driven documents

I am a beginner with the D3 API and I need to create a tree-like structure using a JSON file with hardcoded values. Additionally, I have a servlet that retrieves some values from a database which I want to dynamically convert into JSON in the servlet and s ...

Transforming a Typescript class instance into a JavaScript object

Here is the code snippet I am working with: class A{ test: string constructor(test: string){ this.test = test } } const a = new A("hi") console.log(a) This is what the output looks like: A { test: 'hi' } However, when at ...

What is the reason for polyfilling private fields (#field) in JavaScript on angular builds?

I was eager to incorporate JavaScript private fields into my Angular (v17) application built with Angular CLI. I specified the target as ES2022 in the tsconfig, but after building the app, I discovered that my private field had been poly-filled with a We ...

Is it possible to embed an array within an object by utilizing the name attribute in a form?

I am currently developing a full-stack application where I have a form that submits data to one of my post routes. In this form, all input fields are grouped into req.body.model. This is made possible by adding a name attribute with square brackets around ...

Error: The JSONP request encountered an unexpected token, causing a SyntaxError

Asking for data using AJAX: $.getJSON('https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD&callback=?', function(result) { console.log(result); }); Encountering an error: "Uncaught SyntaxError: Unexpected token :" ...

Refreshing HTML Form upon Submit using JavaScript

I've been searching through various discussions without any luck, but I'm encountering an issue with a form that successfully submits data to a Google Sheet, yet the input fields retain their content after submission. Here is the code: <form ...

Creating a tool to display mouse coordinates as a pointer on an HTML5 canvas

I'm struggling with mouse coordinates while working on canvas in HTML5. My approach involves using JavaScript for drawing on the canvas. Below is my current code to track the mouse pointer within the canvas: $('#canvasID').mousedown(functi ...

After making a request with HttpClient, the response can either be an empty body or a body

Encountering issues with HttpClient while trying to post data, I am faced with two distinct errors: When booking is treated as an object, the error message reads: Backend returned code 400, body was: [object Object]. Converting booking to JSON format by ...

CompleteCalendar JSON string with quoted attributes

Issue Resolved (refer to N69S's comment) (Using Laravel) I am trying to display my events in a calendar view, but I am encountering an issue when parsing my JSON data. The code snippet returned is: "start":"2018-10-01 10:00:00","end":"2018-10-01 ...

Text element within a container of unspecified dimensions

I find it challenging to explain what I have in mind without a visual reference: https://i.sstatic.net/5MSVr.png Some Background - There are certain aspects that can't be altered or shouldn't be changed: On my blog's front page, I utilize ...

javascript issue with fetching data from URL using the GET method

Here is my attempt to fetch a JSON file from a server using asynchronous JavaScript promises. I am experiencing an issue where the result is undefined when using a specific URL, but it works when I use a different URL. Below is the working code with a dif ...

An unanticipated syntax issue has been encountered in the React build chunk files and manifest JSON

I am seeking to host my react application from {baseurl}/admin/. After conducting some research, I came across this solution- Here is my Express code- app.use('/admin/', express.static(path.join(__dirname, '/admin/frontend/'))); app.g ...

Is it possible to simultaneously use the same plugin with various configurations and unique names in Vue?

I'm attempting to utilize the Vue Currency Input plugin, specifically with two different configurations simultaneously: import Vue from 'vue' import VueCurrencyInput from 'vue-currency-input' const options = { globalOptions: { ...

The bootstrap down button refuses to function despite having all the necessary files integrated

My bootstrap drop down button isn't functioning correctly even after ensuring all necessary javascript and popper libraries are included as per npm download. <!DOCTYPE html> <html lang="en"> <head> <title>three grid </title ...

Is it possible to remove a particular div after clicking the delete button, especially if multiple divs are displayed upon clicking the add

var count = 2; var countMax = 5; function adddt() { if (count > countMax) return; document.getElementById('dt-' + count + '').style.display = 'block'; count++; } <link href="https://maxcdn.bootstrapcdn.com/bo ...