Thursday, July 4, 2024
HomeLanguagesJavascriptD3.js group() Method

D3.js group() Method

With the help of d3.group() method, we can group the iterable data structure into a map where the key is defined as the element from iterable and values as an array.

Syntax:

d3.group( iterable, ...keys )

Return value: It returns the map having key as element and value as an array.

Note: To execute the below examples you have to install the d3 library by using this command prompt we have to execute the following command.

npm install d3

Example 1: In this example, we can see that by using the d3.group() method. We are able to get the map from the group iterable where the key is an element and the value as an array.

Javascript




// Defining d3 contrib variable  
var d3 = require('d3');
  
data = [
  {name: "ABC", amount: "34.0",   date: "11/12/2015"},
  {name: "DEF", amount: "120.11", date: "11/12/2015"},
  {name: "MNO", amount: "12.01",  date: "01/04/2016"},
  {name: "XYZ", amount: "34.05",  date: "01/04/2016"}
]
  
var grouped_data = d3.group(data, d => d.name)
  
console.log(grouped_data)


Output:

Map {
‘ABC’ => [ { name: ‘ABC’, amount: ‘34.0’, date: ’11/12/2015′ } ],
‘DEF’ => [ { name: ‘DEF’, amount: ‘120.11’, date: ’11/12/2015′ } ],
‘MNO’ => [ { name: ‘MNO’, amount: ‘12.01’, date: ’01/04/2016′ } ],
‘XYZ’ => [ { name: ‘XYZ’, amount: ‘34.05’, date: ’01/04/2016′ } ]
}

Example 2:

Javascript




// Defining d3 contrib variable  
var d3 = require('d3');
  
data = [
  {name: "ABC", amount: "34.0",   date: "11/12/2015"},
  {name: "DEF", amount: "120.11", date: "11/12/2015"},
  {name: "MNO", amount: "12.01",  date: "01/04/2016"},
  {name: "XYZ", amount: "34.05",  date: "01/04/2016"}
]
  
var grouped_data = d3.group(data, 
        d => d.name, d => d.amount)
  
console.log(grouped_data)


Output:

Map {
  'ABC' => Map { '34.0' => [ [Object] ] },
  'DEF' => Map { '120.11' => [ [Object] ] },
  'MNO' => Map { '12.01' => [ [Object] ] },
  'XYZ' => Map { '34.05' => [ [Object] ] } 
}

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments