Obtain the maximum or minimum value from an associative array using a function and provided parameters

Here is the code I have so far:

<!DOCTYPE html>
<html>
<body>

<button onclick="scanarray('a', 'max')">Test with a, max</button>

<button onclick="scanarray('b', 'min')">Test with b, min</button>



<p id="demo">test</p>

<script>



var array = [{"a":1},{"b":3},{"a":6},{"b":10}];


var max = null;
var min = null;
var value = null;

function scanarray(scanval, searchterm) {

  if (array.length < 1) {
    return -1;
  }

    if(searchterm == "max"){

    max = Math.max.apply(Math,array.map(function(e){return e.scanvalue;}))

    }else if (searchterm == "min"){

    min = Math.min.apply(Math,array.map(function(e){return e.scanval;}))

}else
{document.getElementById("demo").innerHTML = "Only max and min available";}

    if(searchterm == "max"){

        document.getElementById("demo").innerHTML = "Search: " + scanval +"  "+ "Value: " + max;
    }

    if(searchterm == "min"){
        document.getElementById("demo").innerHTML = "Search: " + scanval +"   "+ "Value: " + min;
    }

}
</script>

</body>
</html>

The above code should return a result of a and 6 or b and 3. However, I am receiving NaN as a result for the value part. It works when using "return e.a" in the Math section and only having a as keys.

I am looking to determine the maximum or minimum value of a key I enter as a parameter to the function.

Hope you can assist me with this issue.

Thank you in advance.

TheVagabond

Answer №1

Your code has some naming inconsistencies that need to be addressed. For instance, the function is named scanvalue, but you are trying to access it as a parameter of e (e.scanvalue). It should be renamed to scanval. However, there are still issues present. You cannot access properties "a" or "b" of e using e.scanval. This results in attempting to access a variable of variable.

To rectify this, utilize e[scanval]. This will provide you with the value of "a" or "b". In scenarios where the object does not contain either property, append "|| 0" to ensure you receive the correct value (instead of NaN or undefined). Essentially, use e[scanval] if valid; otherwise, use 0.

Implement the following:

return e[scanval] || 0;

If your boundaries encompass negative values, consider using -9999 or -Infinity.

Answer №2

It appears that you are encountering an issue where e.scanvalue is returning undefined, resulting in Nan.

To resolve this, consider implementing a custom function as shown below:

function extractValues(inputArray){
var result = [];
for(var index = 0; index < inputArray.length; index++)
{
    for(var key in inputArray[index])
    {
        result.push(inputArray[index][key]);
    }
}
return result;
}

Once the custom function is defined, utilize it to find the maximum and minimum values within the array:

maxValue = Math.max.apply(Math,extractValues(array))

and

minValue = Math.min.apply(Math,extractValues(array))

We hope this solution proves to be helpful for your situation!

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

Tips for temporarily preventing a digest cycle when modifying a scope variable

Is there a way to edit an array of objects in AngularJS, linked to the view through ng-repeat, without updating the scope until all objects have been modified? Consider this scenario: I need to update each object in the array and only then reflect the ch ...

Leveraging Flask to pass data to Google Charts with JavaScript

Trying to integrate Google Charts on my website using Flask as the backend. Need help with sending data from Flask to JavaScript. Here's a snippet of where I plan to retrieve data later: @app.route("/") def home(): data = {'Language': &a ...

What is causing the fs.readFile function to give back undefined instead of the expected result?

/** * A function to determine the cost of an employee from a specific data file * @param {string} filePath - the path to the employee data file * @returns {{name: string, cost: number}} - the name and cost of the employee */ function calculateEmployee ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

What steps can be taken to resolve the issue of the <td> element not being allowed as a child of an <a> tag?

https://i.stack.imgur.com/nsdA7.png How can I address these warnings? I utilized the material UI table component and suspect that the warnings are originating from component={Link} to={/patient/${patient.id}} <TableContainer className={styles.tableCo ...

It is impossible to add a new element between two existing elements that share the same parent

I'm attempting to place an <hr> tag between the first and second .field-container. Because they have the same parent, I thought using element1.parentNode.insertBefore(element2, ...) would be the solution. However, it is not working as expected a ...

Is this AJAX request properly formatted?

I am attempting to send an array of variables to my CakePHP action for editing purposes. The array is created from the ids of table rows. Below is the javascript code snippet that can be found in my index.ctp file. <script type="text/javascript"> $( ...

The JSON response from Rails containing multiple lines is not being parsed accurately

I am currently working on a Rails application with a json response using show.js.erb. { "opening": "<%= @frame.opening %>", "closing": "<%= @frame.closing %>"} An issue I encountered is that when @frame.opening contains multiple lines, jQuer ...

Initiating a YouTube video with a click on its thumbnail image - a jQuery tutorial

I am currently working on code that successfully displays YouTube videos. However, I would like the video to start playing when the cover image is clicked. How can I achieve this functionality? Thank you for your help! <div id="video" style="display: ...

Use jQuery to swap out every nth class name in the code

I am looking to update the 6th occurrence of a specific div class. This is my current code <div class="disp">...</div> <div class="disp">...</div> <div class="disp">...</div> <div class="disp">...</div> < ...

What is the method for determining the overall page load time of a website, taking into account the total loading time instead of just the document.ready()

I recently attempted to create a function using either JavaScript or Python with Selenium to measure the page load time of a website. While document.ready() gives me the DOM load time, it may not capture AJAX calls that occur afterwards. I noticed there i ...

In Vue firebase, ensure that the prop is only passed down after it has been

I am facing an issue where I need to pass down the Firebase user as a prop from the root component to my child components. I managed to achieve this by passing the user to my router. However, the problem arises when I wrap my new Vue instance in an onAuthS ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

Tips for dynamically displaying a Material UI dialog with smooth fade effects

I am currently developing a basic application that lists users. Whenever I click on a user, I want to display a dialog box with specific information about that user. I have attempted to achieve this using Material UI's Dialog component in different wa ...

Encountering an "Unmet Peer Dependency" error message while attempting to integrate bootstrap-ui into my Angular project

Currently, my goal is to successfully install angular-ui. Following the tutorials, I have attempted all commands such as: npm install angular-bootstrap However, this command results in an error message: +-- UNMET PEER DEPENDENCY angular@>=1.5 After ...

How to handle the discrepancy between NextJS exporting files with a .html extension, yet in the <Link> component there is no .html specified

I have been working on my NextJS application and I've realized that all the links within it are built using the <Link href="/my-page"><a>My page</a></Link> component. After exporting the app to generate a static site, ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

Babel is failing to transpile the Modal component from material-ui-next to ES5

Issue with Babel transpiling Modal component from material-ui-next Here is my .babelrc configuration: { "presets": ["es2015", "react", "stage-1", "stage-2", "stage-3"] } This is the webpack-config.js setup: var webpack = require('webpack'); ...