Utilizing my function and the Math.max method to analyze a collection of object data

If I have an array containing objects with hundreds of fields structured like the example below:

[
  {
    "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 am attempting to find the maximum value of "h_mag" for all the data points that meet certain criteria using this 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 is functioning properly.

I have made an attempt with the following code:

const maxMOID = Math.max(...filterByPHA(neowise).map(function(x){
  return x.moid_au;
}));

console.log(maxMOID);

My understanding is that this code should apply Math.max to my function filterByPHA(neowise), mapping it to a new function that returns the maximum moid value from the array within filterByPHA(neowise). However, I am encountering a 'TypeError: Cannot read properties of undefined (reading 'map')'. The 'x' in this context is simply a placeholder and I'm uncertain about what needs to be placed there to resolve this issue or if this code is even functional.

Answer №1

To achieve this, you can utilize the Math.max function in conjunction with spread syntax.

See below for an example code snippet:

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));

Answer №2

Give this a try in order to see if it works.

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

When you use console.log(), it will display the output in your console.

The function Math.max() helps find the highest value within a set of numbers.

By using neowise.filter(), you can easily filter out elements from an array by providing a function that returns true or false based on certain conditions. For instance, my function was (value) => value.pha.

.map() is used to transform elements of an array into new values based on a specific function provided as its parameter.

Answer №3

It is advisable to exit your filter function as mentioned.

Avoid using Math.max() with a large amount of data as the stack may overflow when there are around 100,000 items. Additionally, creating two intermediate arrays can be costly.

Instead, I recommend utilizing Array::reduce() for filtering and finding the maximum value in a single operation:

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

You can observe the performance variance based on different numbers 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='));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying entire contents of 2D char array using the C++ cout statement

Currently, I am working on creating a tic-tac-toe game as part of my journey to learn C++. To achieve this, I plan to utilize a 2D char array called playerBoard: char playerBoard[5][14] { {'2',' ','>',' ','_& ...

How can you execute PHP code within another PHP script without triggering a redirect?

I'm faced with a situation where I have two php files, namely abc.php and def.php. My goal is to only display abc.php in the browser URL bar when it executes. Additionally, upon clicking the submit button on my HTML page, abc.php should be triggered t ...

managing the association between keys and values

HTML: <input type="text" ng-model="user.fname" ng-disabled="!allow.fname"/> <input type="checkbox" ng-model="allow.fname" /> <hr/> <input type="text" ng-model="user.lname" ng-disabled="!allow.lname"/> <input type="check ...

Is it possible to obtain a reference to the object with _.find? What is the correct way to update a property of the resultant object

When using lodash find to query an object from an array and then setting a property of that object, the array remains unchanged when printed out. I would appreciate feedback from someone with more experience in handling objects with lodash in JavaScript. ...

What is the process of combining two objects in TypeScript?

As part of my project, I am using two different get requests. The first request returns data in the form of: department: string[] The second get request provides an object structured like this: globalObj: { count: number[], admin: { department: ...

Issue encountered when attempting to alter the action attribute of a form: receiving an error message stating 'undefined is not a function'

I am attempting to dynamically set the action attribute of a form based on the button clicked in order to navigate away from a page. Once the action is updated, the form should be submitted and the new action carried out. Below is my jQuery function: fun ...

CSS3 Transition effects are applied immediately to duplicated elements

My dilemma lies in applying CSS3 Transitions to elements by introducing a new class. Markup <div id="parent"> <div class="child"> </div> </div> CSS .child { background: blue; -webkit-transition: background 4s; ...

Retrieve information from the SEMrush API response dataset

I am currently facing an issue with extracting data from the SEMrush api, as their response does not adhere to the standard "key:value" JSON format. Instead, each key and value is displayed in separate rows as shown below. Request Example: http://api.sem ...

Event bubbling does not occur in elements outside of the DOM

I am facing an issue with a DOM element that has not been added to the DOM yet, but I want to trigger a DOM event on it. The event is not supposed to bubble up, however, when using jQuery, it does. This behavior seems odd to me. This strange phenomenon c ...

A guide on iterating through an array to generate a new array within the loop, filled with elements from the original array

Hey there! I'm currently working on a game and have run into a roadblock with arrays and loops in PHP. Specifically, I need to create a function that generates a stack of crystal IDs based on a given size and ratio. The ratio refers to the proportion ...

How do I use jQuery to remove a dynamically added class from the page's header?

When using an inline editor to modify css classes, I encounter the need to remove and then re-add a class definition after making changes. Additionally, users have the option to delete elements, so it's important that the definition is also deleted. ...

What is the correct way to apply a concatenated element id when using the .click() function in

Having an issue with assigning buttons to input boxes in a loop. When using concatenated element IDs with the .click() method, the buttons won't click for some reason. The following code works: document.getElementById("streamInput1") .addEventLi ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

What is the method for a function to process a NumPy array input that is not separated by commas?

I created a custom function to manipulate a 2D NumPy array: def modify_array(state, row, col): state = np.array(state) state[row][col] = 0 return state To validate the function, I used the following data structure: state = np.array([[1, 1, 1, ...

The jQuery onchange function does not have the ability to limit the input to only

When using the script to sum the input value, everything seems to be working fine. However, I am facing an issue where clicking up and down on the "input#total_selfmark" does not change the value. Additionally, when I manually type in a number, the "input# ...

Tips for utilizing the Raycaster in tandem with a CombinedCamera?

When trying to implement a Raycaster for selection, I encountered an issue where it worked fine with a PerspectiveCamera but not with a CombinedCamera. It appears that the Raycaster does not support CombinedCamera, so I made some modifications in the thre ...

Trouble Arising from the Lack of Coordination Between CSS Transition and JavaScript Update Triggered by Element

I'm currently working on a web development project that involves a list of clickable elements. When one of these elements is clicked, it should become active and trigger a CSS transition (such as a transform) with a duration of 200ms. Additionally, I ...

The event listener $(window).on('hashchange', function() is causing issues on my Internet Explorer 9 browser

My website utilizes the code $(window).bind('hashchange', function ()) to check if a redirect is necessary. It is working perfectly fine in Firefox, but I am facing issues with IE9. $(window).bind('hashchange', function () { ...

ReactPlayer allows for the simultaneous playback of two files

I am trying to simultaneously play two files in reactjs using ReactPlayer. The first file is a video music clip that includes human voice audio, while the second file is music only without the human voice. My issue is that when I run the code provided, ei ...

Reactjs error: Trying to map over undefined property in functional component

I am currently working on a react application that is designed to retrieve images from an API call. However, I have encountered a problem where I am receiving the following error in my imageList.js file: "TypeError: Cannot read property 'map' of ...