In JavaScript, it is not possible to retrieve the maximum or minimum value of an array

Hey there! I'm having some trouble finding the minimum and maximum values in an array. Can you help me figure out what's going on with my code?

    var repeated, studentsArray = [], marksArray = [];
while (repeated !== 'n' && repeated !== 'N'){
    studentsArray.push(prompt("Enter Student Name: "));
    marksArray.push(parseInt (prompt("Enter Student mark: ")));
    repeated = prompt ("Do you want to enter another student: y/n");
}  

function findMinimum (marksArray){
    var minVal = Number.MAX_VALUE;
    for(var i = 0; i < marksArray.length; i++){
       if(Number(marksArray[i]) < minVal)
           minVal = Number(marksArray[i]); 
    }
    return marksArray;
}
var smallestValue = findMinimum(marksArray);

function findMaximum (marksArray){
    var maxVal = Number.MAX_VALUE;
    for(var i = 0; i > marksArray.length; i++){
       if(Number(marksArray[i]) < maxVal)
           maxVal = Number(marksArray[i]); 
    }
    return marksArray;
}
var largestValue = findMaximum(marksArray);

    document.write(largestValue);

Answer №1

If you want to customize the behavior of JavaScript's Array type, you could do so by adding custom methods like this:

Array.prototype.smallest = function(comparator) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparator = (comparator || Math.min);

    var result = this[0];
    for (var i = 1; i < this.length; i++)
        result = comparator(this[i], v);  

    return result;
}

Array.prototype.largest = function(comparator) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparator = (comparator || Math.max);

    var result = this[0];
    for (var i = 1; i < this.length; i++)
        result = comparator(this[i], v);    

    return result;
}

You can then use these custom methods as follows:

var smallestValue = yourArray.smallest();
var largestValue = yourArray.largest();

Check out the example on jsbin: http://jsbin.com/yoyecono/1/edit

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

Effortlessly Transition to Full Screen with Div Expansion on Click

I'm currently working on creating a smooth transition for a div to expand fullscreen when clicked. My goal is to achieve a similar effect as the case studies on this website: Although my code can make the div go fullscreen, there's an issue with ...

Simplified method for creating Angular templates

Take a look at this code snippet my_app.run( [ '$templateCache' , function( $templateCache ) { var template = "" + "{{ item.name }}" + "<ul ng-if='item.sub'>" + "& ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

What is the best method to extract information from JavaScript tables using Python and Selenium?

As a beginner in Python, JavaScript, and Web-Scraping, I am facing the challenge of extracting data from tables on a specific webpage (https://www.mcmaster.com/cam-lock-fittings/material~aluminum/) and saving it into a csv file. https://i.sstatic.net/xQBO ...

identify the alteration in course

At the moment, I'm engaged in a school assignment during my high school years. I'm interested in finding out if it's possible to access real-time data on different types of manoeuvres, such as turning left or right. Is there a specific funct ...

Unleashing the Power of Aurelia's HTML Attribute Binding

I need to bind the "required" html attribute in my template and model. Along with passing other information like the label value using label.bind="fieldLabel", I also want to pass whether the element is required or not. However, simply using required="tr ...

Guide on how to retrieve a value using image.onload on the client side

I have encountered an issue with exporting a png image from an svg element using Blob. The problem arises when clicking the anchor tag to export the image, as the content is not rendered due to the asynchronous method (image.onload()) being called after th ...

I have created an Express.js application. Whenever I visit a page, I consistently need to refresh in order for the variables to appear correctly

Hello, I'm seeking some assistance. Despite my efforts in searching for a solution, I have not been successful in finding one. I've developed an application using Express.js that includes a basic form in jade. The intention is to display "Yes" i ...

Watch as objects materialize after using the zoom function in THREE.JS

I am facing an issue with THREE.JS involving the addition of 3D text to my scene using the following code: var loader = new THREE.FontLoader(); loader.load( '3rdparty/three.js/fonts/helvetiker_regular.typeface.json',function ( font ) { var ma ...

Utilize information stored in a database to automatically navigate to a different webpage

I am currently working with PHP, HTML, and a mySQL database. Here are my current project requirements: Retreive specific data from the database and output it. Compare this data with predetermined values. If the data falls outside of the specified range, ...

Enforce a restriction on the user's input value for the amount field within a React application

I'm looking to limit the user from entering more than 50000 in the input value. How can I achieve this using React? I am currently handling this on the onchange event. onPaymentAmountChanged = (e) => { let inputValue = e.target.value; if (i ...

Controlling the v-model value of a v-select within a v-for loop

I have set up a table of members using a v-for loop, and certain users have the ability to manage other members based on their role. I have implemented some checks to prevent unauthorized roles from intervening, but the full list of checks is carried out o ...

Where is the appropriate location to insert a <script> tag in NextJs?

I am facing a challenge in my NextJs application when trying to include the <script> code. I attempted to add it in a .js file but it did not work as expected. In traditional React applications, we typically use the index.html file to incorporate sc ...

What are some tips for managing the hover effect using CSS3?

Here's a demonstration of my current setup. When you hover over the black box, a transition occurs and reveals my tooltip. However, I only want the tooltip to appear when hovering over the black box itself. Currently, the transition also triggers if y ...

Fetching data from a database for Vue.js using the Summernote editor

I previously inquired about integrating summernote with vue.js and received a helpful response here. It worked seamlessly with v-model binding. However, I encountered an issue when attempting to load data from the database for an edit page. The data was n ...

Experiencing difficulty in adding a sub-document to an array within a parent

I am currently working with a users model that incorporates a locationsSchema: const locationSchema = require('./location.js'); const userSchema = new mongoose.Schema({ email: { type: String, unique: true, required: true, }, t ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Set a dynamic Active Class on various divisions by utilizing their respective indexes

I have two divs with the same class. When I click on an anchor tag within one of the elements, I want to add a class to the corresponding position in the second div as well. Mirror: JSFiddle Here is the jQuery code snippet: $(document).on('click ...

Transform a text with HTML tags into sentences while preserving the separators in Javascript

Here is a unique string with some embedded HTML code: This is the first sentence. In the second sentence, there is a <a href="http://google.com">Google</a> link! The third sentence may have an image like <img src="http://link.to.image.com/h ...

What is the method to rotate an SVG icon contained within a button when clicked?

I'm attempting to incorporate a CSS animation into an SVG that is enclosed within a button. Example <button class="spin"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ari ...