I created an array in Javascript that should be all numbers. When I use Math.max on it, the function returns NaN. I am stumped.
First, I know the documentation says Math.max returns NaN when one of the arguments cannot be converted to a number, so I think that is happening. I cannot understand what that is.
Here d is an array of objects. The objects are key-value pairs. I want to put all the values of each object in the d array into one new array and then find the max. Here is how I make my new array valsarr:
var valsarr = [];
d.map(function(row){
Object.keys(row).forEach(function(key) {
row[key] = Number(row[key]);
valsarr.push(Number(row[key]));
});
});
I know using Number twice is redundant, but I added the second to be extra careful. I tried parseInt and + in its place and had the same result.
Then I try to obtain the max of that array and print:
var mymax = Math.max.apply(Math, valsarr)
console.log(mymax);
It prints NaN
As part of the debugging process, I tried filtering the array to find non-numbers in it, but I get nothing. My code for that task could be faulty too, however. Here it is:
function isNotNumber(value) {
return (typeof(value) !== "number");
}
var badarr = valsarr.filter(isNotNumber);
console.log('Filtered Array\n', badarr);
It prints an array of length 0. I believe that means it found no non-number values in the array.
Two more notes: The original data in d contains thousands of values. It comes from .csvs. So I don't want to hunt through all the values to find ones that are not numbers. I can easily see the original d object and the valsarr array do have numbers in them. Second, it works when I load in one of the .csvs I am using but not any of the others.
But again, with any of the .csvs, both d and valsarr have at least some numbers in them when I scan through them to check, so the first code block is doing something, at least every time.
Any help would be greatly appreciated.
typeof NaNalso returnsnumber. Try to useisNaN().dvalsarr.filter(v => ! isNaN(v));var badarr = valsarr.filter(isNaN)d.forEachinstead ofd.map.