Reputation: 29
I am new to D3 and Javascript community. I have an array of objects(countries) and each object consists of years represented by key and its value(incomes).
How to get the minimum and maximum value of incomes across all the objects and its key to set the color legend?
Please find the link https://observablehq.com/d/287af954b6aaf349 of the project, hope it would help to explain the question.
Thank you for reading the questions.
Upvotes: 1
Views: 962
Reputation: 5167
Another useful method backed in d3 is the d3.extent()
function check this article
Upvotes: 1
Reputation: 13129
To get the global maximum, you can use
const max = d3.max(
countries.map(country =>
d3.max(Object.values(country))));
// 179000
What it does is iterate over the countries, grabbing from each country the maximum of all the values. Then, it takes the maximum of these maxima and returns that.
To also get the corresponding year, it becomes more complex. You can use Object.entries
to get the key value pair, instead of just the value.
You can then manually loop over each country, updating the max value, and the corresponding year as you go
data.reduce((max, country) => {
const newMax = d3.max(Object.values(country));
if(newMax > max.value) {
return {
year: Object.entries(country).find(([year, value]) => value === newMax)[0],
value: newMax,
};
}
return max;
}, {value: 0});
// {year: "2040", value: 179000}
Upvotes: 2