I am trying to find the max value of id:x in an associative array that is located in a text file located in the same folder as my script.
I found 2 working examples, one finds the max value and the other reads the array from a text file. I am trying to put them together, but the output is NaN (Not a Number). I am not sure what is wrong with the script.
Script that reads in the array
Script that finds max value
Script combined.
I am new to javascript, so I am open to other methods to accomplished the same task.
I found 2 working examples, one finds the max value and the other reads the array from a text file. I am trying to put them together, but the output is NaN (Not a Number). I am not sure what is wrong with the script.
Script that reads in the array
JavaScript:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var data = rawFile.responseText;}
alert(data);
}
}
rawFile.send(null);
}
readTextFile("test_array.txt");
Script that finds max value
JavaScript:
data = [
{
"id":1,
"meetdate":"20180830"
},
{
"id":2,
"meetdate":"20180920"
},
{
"id":3,
"meetdate":"20181025"
}
]
var max = Math.max.apply(null,
Object.keys(data).map(function(e) {
return data[e]['id'];
}));
var newid = max +1;
alert(newid);
Script combined.
JavaScript:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var data = rawFile.responseText;}
//alert(data);
var max = Math.max.apply(null,
Object.keys(data).map(function(e) {
return data[e]['id'];
}));
var newid = max +1;
alert(newid); //Output desired
}
}
rawFile.send(null);
}
readTextFile("test_array.txt");
I am new to javascript, so I am open to other methods to accomplished the same task.