D3.js group() 方法
在d3.group()方法的帮助下,我们可以将可迭代的数据结构分组到一个映射中,其中键定义为可迭代的元素,值定义为数组。
句法:
d3.group( iterable, ...keys )
返回值:它返回以 key 为元素,value 为数组的 map。
注意:要执行以下示例,您必须使用此命令提示符安装 d3 库,我们必须执行以下命令。
npm install d3
示例 1:在此示例中,我们可以通过使用d3.group()方法看到这一点。我们能够从可迭代的组中获取映射,其中键是元素,值是数组。
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)
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)
输出:
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′ } ]
}
示例 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)
输出:
Map {
'ABC' => Map { '34.0' => [ [Object] ] },
'DEF' => Map { '120.11' => [ [Object] ] },
'MNO' => Map { '12.01' => [ [Object] ] },
'XYZ' => Map { '34.05' => [ [Object] ] }
}