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.
3
Answers
Try it like this. That should work.
console.log() obviously print into your console.
Math.max() finds the greatest value.
neowise.filter() can filter your array. Therefore you need to provide a function a parameter which returns a bool (true => value stays).
My function was
(value) => value.pha
..map() maps the value to another value. It also needs a function as its parameter which returns the new value.
As mentioned you should return from your filter function.
But I would suggest avoid using
Math.max()
with big amount of data, since about 100_000 items the stack is overflowed.Moreover you create 2 intermediate arrays, which expensive.
I suggest to use
Array::reduce()
to have filtering and finding the max in 1 operation:And you can see the performance difference with different number of elements:
You can use
Math.max
function along with spread syntax to achieve this.Refer to the following code :