I have an array of objects such as this, and I want to find the max value (5.7) in this array of objects.
I have tried d3.max(data) but it only returns the first value. I figured that I might need to convert this array of objects into a list of values instead to work? I am not sure how to do it.
let data =
[{2017: 5.2},
{2018: 5.7},
{2019: 5.1},
{2020: 4.8},
{2021: 0}]
Thank you.
CodePudding user response:
Idiomatically, with D3 you'll probably want to use common keys, something like:
{ year: 2017, value: 5.2 }
However, in your specific case here, you can still use d3.max, you'll just need to use an accessor function that handles a dynamic object key for every object in the array:
let data =
[{2017: 5.2},
{2018: 5.7},
{2019: 5.1},
{2020: 4.8},
{2021: 0}];
let max = d3.max(data, function(datum) {
return datum[Object.keys(datum)[0]]
});
console.log(max);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
As noted though, generally you'll probably want to separate year and associated value in a single object, which you could do with:
let data =
[{2017: 5.2},
{2018: 5.7},
{2019: 5.1},
{2020: 4.8},
{2021: 0}];
data = data.map(function(datum) {
let year = Object.keys(datum)[0];
let value = datum[year];
return { year, value }
});
console.log(data);
No you can find the extent of years and values much easier than you would otherwise, eg: d3.max(data, d=>d.year)
or d3.max(data,d=>d.value)
.