skip to Main Content

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


  1. Try it like this. That should work.

    console.log(Math.max(... neowise.filter((value) => value.pha).map((value) => value.moid_au)))
    

    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.

    Login or Signup to reply.
  2. 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:

    neowise.reduce((r, item) => (item.pha && item.h_mag > r && (r = item.h_mag), r), -Infinity);
    

    And you can see the performance difference with different number of elements:

    ` Chrome/121
    -----------------------------------------------------------------------------
    >              n=1       |      n=10       |     n=100      |     n=1000     
    reduce   1.00x x100m 227 | 1.00x x100m 852 | 1.00x x10m 663 | 1.00x x100k  93
    map      6.92x  x10m 157 | 8.23x  x10m 701 | 7.95x  x1m 527 | 6.44x x100k 599
    -----------------------------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    const $chunk = () => [{
      "designation":"419880 (2011 AH37)",
      "discovery_date":"2011-01-07T00:00:00.000",
      "h_mag":Math.random()*100,
      "moid_au":0.035,
      "q_au_1":0.84,
      "q_au_2":4.26,
      "period_yr":4.06,
      "i_deg":9.65,
      "pha":Math.random()>.4,
      "orbit_class":"Apollo"
    }];
    
    const $input=[];
    
    // @benchmark map
    Math.max(...$input.filter(x => x.pha).map(x => x.h_mag));
    
    // @benchmark reduce
    
    $input.reduce((r, item) => (item.pha && item.h_mag > r && (r = item.h_mag), r), -Infinity);
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
  3. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search