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;
})