I'm currently troubleshooting a code snippet that involves determining the minimum and maximum values within a collection. Everything was functioning well until I added 0 values to the collection, which caused the function to return NaN. The function works as expected when run without any 0 values.
const minVal = Math.min(...this.wells.map(d => Number(d.valueText) || Number(d.value)));
const maxVal = Math.max(...this.wells.map(d => Number(d.valueText) || Number(d.value)));
For instance, if we have values ranging from 2 to 0.00003 to 0, the minimum value should be 0 and the maximum value should be 2.
If the values were from 10 to 0.000000001 or from 1 to 10000, the function would work correctly.
let wells = [];
wells.push({
posCol: 0,
posRow: 0,
valueText: 2
});
wells.push({
posCol: 1,
posRow: 0,
valueText: 4
});
wells.push({
posCol: 2,
posRow: 0,
valueText: 0
});
const minVal = Math.min(...wells.map(d => Number(d.valueText) || Number(d.value)));
const maxVal = Math.max(...wells.map(d => Number(d.valueText) || Number(d.value));
console.log(minVal);
console.log(maxVal);
Below is an example of working code:
let wells = [];
wells.push({
posCol: 0,
posRow: 0,
valueText: 2
});
wells.push({
posCol: 1,
posRow: 0,
valueText: 4
});
wells.push({
posCol: 2,
posRow: 0,
valueText: 1
});
const minVal = Math.min(...wells.map(d => Number(d.valueText) || Number(d.value)));
const maxVal = Math.max(...wells.map(d => Number(d.valueText) || Number(d.value)));
console.log(minVal);
console.log(maxVal);
SOLUTION FOR ANYONE ENCOUNTERING THIS ISSUE (See @VLAZ Explanation)
let wells = [];
wells.push({
posCol: 0,
posRow: 0,
valueText: 2
});
wells.push({
posCol: 1,
posRow: 0,
valueText: 4
});
wells.push({
posCol: 2,
posRow: 0,
valueText: 0
});
const minVal = Math.min(...wells.map(d => Number(d.value) || Number(d.valueText)));
const maxVal = Math.max(...wells.map(d => Number(d.value) || Number(d.valueText)));
console.log(minVal);
console.log(maxVal);
The issue arose from the fact that the value 0 was being evaluated as falsy, causing the function to default to an undefined property, resulting in NaN. The solution involved swapping the positions of the two number checks.