Assuming an array of objects that has a couple hundred fields that look like this
[
{
"designation":"419880 (2011 AH37)",
"discovery_date":"2011-01-07T00:00:00.000",
"h_mag":19.7,
"moid_au":0.035,
"q_au_1":0.84,
"q_au_2":4.26,
"period_yr":4.06,
"i_deg":9.65,
"pha":true,
"orbit_class":"Apollo"
}
I'm trying to show the maximum "h_mag" value for all of the data points that I have isolated with the following function:
function filterByPHA (neowise){
for (let i = 0; i < neowise.length; i++) {
let neo = neowise[i];
if (neo.pha === true) {
console.log(`${neo.designation}: ${neo.orbit_class}`);
}
}
}
filterByPHA(neowise);
The function works.
I have tried the following:
const maxMOID = Math.max(...filterByPHA(neowise).map(function(x){
return x.moid_au;
}));
console.log(maxMOID);
What I think this code should be doing is 'applying' Math.max to my function ('filterByPHA(neowise)' and 'mapping' it onto a new function that returns the maximum moid value for the array inside 'filterByPHA(neowise)'. However, the .map is giving me a 'TypeError: Cannot read properties of undefined (reading 'map')'. The 'x' is just a placeholder. I'm not actually clear on what I need to be putting there to make this code work, or if even it could be a functional bit of code.
You can use Math.max
function along with spread syntax to achieve this.
Refer to the following code :
function filterByPHA(neowise) {
let filteredPHA = neowise.filter(neo => neo.pha === true);
if (filteredPHA.length > 0) {
let maxHMAG = Math.max(...filteredPHA.map(neo => neo.h_mag));
console.log(`Maximum h_mag for PHA objects: ${maxHMAG}`);
} else {
console.log("No PHA objects found");
}
}
const neowiseData = [
{
"designation": "419880 (2011 AH37)",
"discovery_date": "2011-01-07T00:00:00.000",
"h_mag": 19.7,
"moid_au": 0.035,
"q_au_1": 0.84,
"q_au_2": 4.26,
"period_yr": 4.06,
"i_deg": 9.65,
"pha": true,
"orbit_class": "Apollo"
},
{
"designation": "419880 (2011 AH38)",
"discovery_date": "2011-01-07T00:00:00.000",
"h_mag": 20.7,
"moid_au": 0.035,
"q_au_1": 0.84,
"q_au_2": 4.26,
"period_yr": 4.06,
"i_deg": 9.65,
"pha": true,
"orbit_class": "Apollo"
}
];
console.log(filterByPHA(neowiseData));