Reputation: 45
Ok my problem is that I loaded this json file in a script. I am also using d3.js
[{"name":"object1","income":[[2013,100], [2014, 450], [2015,175]]}, {"name":"object2","income":[[2013,230], [2014, 250], [2015,375]]}]
The income array is composed of a year and the income value. [2013,100] implies that the income was equal to 100 in 2013. My problem is that I want to obtain the maximum value of the income of the dataset. In this case the maximum is equal to 450. Is it possible to do this with the d3.max function
Thanks a lot.
Upvotes: 0
Views: 437
Reputation: 386670
A solution, the question was for me unclear, get the max income for every year, or the max income from all years.
var data = [{ "name": "object1", "income": [[2013, 100], [2014, 450], [2015, 175]] }, { "name": "object2", "income": [[2013, 230], [2014, 250], [2015, 375]] }],
// max gouped by year
max = data.reduce(function (max, o) {
o.income.forEach(function (a) {
max[a[0]] = Math.max(max[a[0]] || a[1], a[1]);
});
return max;
}, {}),
// single value taken from the year object
maxTotal = Object.keys(max).reduce(function (m, k) {
return Math.max(m, max[k]);
}, Number.MIN_VALUE),
// single run max from all objects and years
maxAll = data.reduce(function (m, o) {
return o.income.reduce(function (mm, a) {
return Math.max(mm, a[1]);
}, m);
}, Number.MIN_VALUE);
console.log('max', max);
console.log('maxTotal', maxTotal);
console.log('maxAll', maxAll);
Upvotes: 0
Reputation: 109242
Yes you can do this quite easily with D3, using the second argument to d3.max
which takes an element and returns the part of it to take the max of:
var maxIncome = d3.max(data, function(d) {
return d3.max(d.income, function(e) { return e[1]; });
});
Upvotes: 2
Reputation: 388396
In modern browsers
var data = [{
"name": "object1",
"income": [
[2013, 100],
[2014, 450],
[2015, 175]
]
}, {
"name": "object2",
"income": [
[2013, 230],
[2014, 250],
[2015, 375]
]
}];
var max = Math.max.apply(Math, data.map(function(item) {
return item.income.reduce(function(a, b) {
return a > b[1] ? a : b[1]
}, 0)
}));
snippet.log(max)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Upvotes: 1
Reputation:
How about plain old javascript;
var max = 0;
var dataset = [{"name":"object1","income":[[2013,100], [2014, 450], [2015,175]]}, {"name":"object2","income":[[2013,230], [2014, 250], [2015,375]]}];
dataset.forEach(function(obj) {
obj.income.forEach(function(arr) {
var val = arr[1];
if(val > max) {
max = val;
}
});
});
console.log(max);
Upvotes: 2