I'm trying to use D3 to find the lowest value in my dataset. However, I also have values that are 0, but I want D3 to find the lowest value that is not 0.
Currently I am using:
d3.min(data, function(d) {return d.houseValues; })
But obviously this returns 0 sometimes, when a 0 is found.
Is there a way to do this? Or is the only solution to build a normal for-loop with an if-statement to ignore the 0 values..?
Thanks!
I'm trying to use D3 to find the lowest value in my dataset. However, I also have values that are 0, but I want D3 to find the lowest value that is not 0.
Currently I am using:
d3.min(data, function(d) {return d.houseValues; })
But obviously this returns 0 sometimes, when a 0 is found.
Is there a way to do this? Or is the only solution to build a normal for-loop with an if-statement to ignore the 0 values..?
Thanks!
Share Improve this question edited Mar 22, 2022 at 19:46 LexMulier asked Mar 25, 2015 at 17:05 LexMulierLexMulier 2734 silver badges13 bronze badges3 Answers
Reset to default 8You can use the constant Infinity
, since Math.min(Infinity, someNumber)
always return someNumber
(unless someNumber
is also infinity). So it'll look like this:
smallest = d3.min(data, function(d) {return d.houseValues || Infinity; })
If needed, you can check smallest == Infinity
, which would be true
in the case that all house values were 0.
Try filtering the data to remove zeroes first, e.g.
var noZeroes = data.filter(function(d) { return d.houseValues !== 0; });
d3.min(noZeroes, function(d) {return d.houseValues; })
Building on @meetamit's answer, if you want smallest
to be undefined
when the data has all zeros, use undefined
instead of Infinity
.
d3.min()
"ignores undefined, null and NaN values".
const data1 = [
{
houseValues: 0,
},
{
houseValues: 100000,
},
{
houseValues: 150000,
},
];
const data2 = [
{
houseValues: 0,
},
{
houseValues: 0,
},
];
smallest = d3.min(data1, function(d) { return d.houseValues; });
smallestNonZero = d3.min(data1, function(d) { return d.houseValues || undefined });
smallestAllZeros = d3.min(data2, function(d) { return d.houseValues || undefined });
console.log(smallest);
console.log(smallestNonZero);
console.log(smallestAllZeros);
<script src="https://cdnjs.cloudflare./ajax/libs/d3/5.7.0/d3.min.js"></script>