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

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

Retrieving JSON information from asynchronous JavaScript and XML (AJAX)

I am struggling with making a URL that contains JSON Data work properly. The issue lies in the data field - I am unsure of what to input here as it is currently undefined. My goal is to store an array of the JSON data received from the ajax request. What ...

Refreshing material ui select choices based on user input

Just getting started with Reactjs and I need some help. I have a material ui select element that has default values set, and when I click the 'ADD USER' button and submit, I can add new values to the select element. I'm also able to delete o ...

Tips for positioning a highcharts pie chart and legend in the middle of a page

I'm struggling to center my highchart data in a node/react single page application. Currently, it appears off-center like this: https://i.stack.imgur.com/ccR6N.png The chart is floating to the left and I would like to have everything centered within ...

Utilizing jQuery to gather the values of all checkboxes within each group and dynamically adding them to a span element for counting purposes

I am currently working on a project that involves sets of groups with checkboxes. My goal is to retrieve the value of each checkbox when checked and add this value to a counter span element located beside it. However, I have encountered an issue where clic ...

CSS or jQuery: Which is Better for Hiding/Showing a Div Within Another Div?

Show only class-A at the top of the page while hiding all other classes (x,x,c). Hide only class-A while showing all other classes (x,x,c). Is it possible to achieve this? <div class="x"> <div class="y"> <div class="z"&g ...

Submit an Ajax form to process data in PHP upon selecting a radio button

I am troubleshooting an issue with a form that is not submitting data to processor.php for processing and storing responses in a database. Ensuring that the form submission does not cause a page refresh is crucial, as there is an iframe below the form tha ...

JavaScript Time and Date Formatting

I'm pretty new to programming, especially in Javascript. Can someone help me simplify my code? I'm trying to create a dropdown for months and an input field for the year. Is there a more efficient way to make the month select box? Also, how can ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...

Build an object using a deeply nested JSON structure

I am working with a JSON object received from my server in Angular and I want to create a custom object based on this data. { "showsHall": [ { "movies": [ "5b428ceb9d5b8e4228d14225", "5b428d229d5b8e4 ...

JS values are completely out of sync

I am currently computing values, capturing them in a snapshot, and then sending them within an interval. However, the problem lies in the fact that the total sum is growing at an unexpectedly high rate. Here are the calculations being performed: // Ass ...

Having difficulty extracting image and product names from Amazon or Flipkart pages using Jsoup

I'm having trouble retrieving the main image and product name from Amazon or Flipkart using Jsoup. This is my Java/Jsoup code: // For amazon Connection connection = Jsoup.connect(url).timeout(5000).maxBodySize(1024*1024*10); Document doc = connectio ...

Identifying geometric coordinates within Canvas

Currently, I am adding drag and drop functionality to my HTML5 Canvas application. I have encountered a challenge in determining how to detect if the shape being clicked on is not a rectangle or square. For instance, within my 'mousedown' event h ...

Design a background image that is optimized for both high-resolution retina displays and standard non-ret

Scenario I am working on a web page where I want the background image to be fixed, covering the entire screen or window (excluding tablets and smartphones). The background image has been created using ImageShack. Everything is running smoothly so far. T ...

Implementing an event handler within a functional component using hooks in React

I'm currently exploring functional components and hooks. I have a component that retrieves an array of quotes from an API and is supposed to randomly select one to pass as a prop to a child component named "Quote". import React, {useState, useEffect} ...

Having trouble with JavaScript's XMLHttpRequest returning an 'undefined' string on the first run of my script. I need to find a way to ensure that it loads correctly during

Before we dive in, a quick disclaimer: My knowledge of JS is limited, and I typically learn on the go when creating scripts. However, my usual method didn't work this time. Currently, I'm working on a small JS script that will function as a book ...

Having trouble with jQuery focus not functioning properly?

I've been attempting to implement a focus function on a specific input in order to display a div with the class name .search_by_name when focused. However, I'm encountering issues and would appreciate it if someone could review my code to identif ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

The issue with the trigger function in jQuery is specifically affecting Chrome browser

When attempting to load a modal window using a link like , I am encountering issues in Chrome, Safari, and IE. However, Opera and FF are functioning properly. The modal window is being called as an iframe. Other buttons that are supposed to open the modal ...