I am having trouble getting the minimum value as it keeps displaying 0. However, when using Math.max(), it correctly displays the maximum value. Can anyone explain why this is the case?

Why am I not getting the minimum value when it displays 0, but Math.max() correctly shows the maximum value?

function findMin(ar) {
  var min_val = 0;
  for(var i = 0; i < ar.length; i++) {
    min_val = Math.min(min_val,ar[i]);
  }
  document.write(min_val);
}
findMin([14,99, 10, 18,19, 11, 34]);

Answer №1

When comparing the variable to `min_val`, it consistently returns 0. This is due to the fact that in an array, 0 is lower than any other value present. Therefore, `min_val` will always remain as 0 since it cannot find a lower value within the array.

As a solution, I propose the following code:

let ar =[14,99,10,18,19,11,34]
let min_val = Math.min(...ar)
console.log(min_val)

This approach is also more concise compared to using a for-loop.

Answer №2

To achieve the desired outcome, you should begin by setting the minimum value to an extremely large number (Infinity).

    var min_value = Infinity;
    for(var i = 0; i < arr.length; i++) {
         min_value = Math.min(min_value, arr[i]);
            }
document.write(min_value);
}
values([14,99, 10, 18,19, 11, 34]);

This script will output Infinity if the array is empty, or the smallest value within the given input.

Answer №3

Math.min() can accept arguments like Math.min(-2, -3, -1) or with an array like Math.min(...arr). In this case, you are passing the arguments as

Math.min([14,99, 10, 18,19, 11, 34], 0)
where 0 is the minimum value. Therefore, the output would be 0. Since Math.min() already finds the minimum value, there's no need for a loop. The solution can be written as:

function values(ar) {
    var min_val = Math.min(...ar);
    //document.write(min_val);
    return min_val
}
console.log(values([14,99, 10, 18,19, 11, 34]))

Alternatively (to match your specific case):

function values(ar) {
    var min_val = Math.min(...ar);
    
    document.write(min_val);
}

In its shortest form:

document.write(Math.min(...ar));

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

What happens when you click on paper-tabs in a polymer?

Struggling to get click events to fire on <paper-tabs> and <paper-tab>. Interestingly, when manually adding event listeners in Chrome's developer tools, it works fine. But the same code doesn't seem to work in my application: // app. ...

What is the best method to reset the chosen option in a dynamic select dropdown using React?

I have a form set up with a Select dropdown that is populated dynamically from the server. The issue I'm facing is that after selecting an option from the dropdown and then saving or canceling the form, the selected value remains in the field when I ...

Tips for resolving the issue of missing metadata for open graph and Twitter cards in a Next.js project

Having trouble with error messages while running the build version in Next.js. I've added meta tags to the layout, but the issue persists. As a newcomer to Next.js, I'm looking for guidance on how to fix this problem. Any help or advice on troubl ...

What is the best way to remove current markers on google maps?

This is how I implemented it in my project. The issue I'm facing is that the clearAirports function does not seem to clear any existing markers on the map or show any errors in the Google console. googleMaps: { map: null, init: function () { ...

Verify if the value in the array is both set and null

How can I determine if an array variable is both set and null? $a = array('a'=>1, 'c'=>null); I have a function that checks if a specific key in an array is set and if its value is null: function check($array, $key) { if (i ...

The Access-Control-Allow-Headers in preflight response does not permit the use of the request header field authorization when sending an HTTP GET request from JavaScript to the Slack API

While I acknowledge that there may be similar queries out there, I believe mine has a unique angle. My goal is to send a GET request to the Slack API using an HTTP request. Here is the code snippet I am working with: import useSWR from "swr"; ...

Combine various canvases into a single one (for exporting purposes) with pure Javascript

I'm currently faced with a unique challenge involving the creation of around 200 canvases, each showcasing an image captured from the user's webcam as part of an experimentation process for the "photo finish" technique. My task now is to export ...

Exploring Angular 2 Routing across multiple components

I am facing a situation where I have an app component with defined routes and a <router-outlet></router-outlet> set. Additionally, I also have a menu component where I want to set the [routerLink] using the same routes as the app component. How ...

Navigating from the online realm to leisure activities

As a web developer with knowledge in PHP, Python, Ruby, and JavaScript, I've tackled various web projects but now I have a strong desire to dive into game development. It may seem like a big leap, but I'm determined to learn and explore this new ...

Is there a way to incorporate a unique code onto my webpage, such as the famous Konami code?

I'm on the lookout for a unique twist on the typical Konami code questions. Instead of triggering an alert or redirecting to a different page, I want to hide a specific paragraph on my main page (index.html) by default. When the user enters the Konami ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

Issue with displaying value after rendering

After fetching pool data from the constants file, my task was to create a featured vault - the one with the highest APY Reward value obtained from the API. Even though I successfully fetched all three values and performed the calculations, I am facing an i ...

Tips for obtaining the retrieved URL from an ajax call

How can I extract only the returned URL from an ajax request? I have tried implementing it like this: $.ajax({ type: "GET", dataType : "jsonp", async: false, url: $('#F ...

When encountering issues with the select element, such as when it is combined with AJAX or Bootstrap,

When attempting to use a foreach loop within the <select><option> ... </option></select> element with jquery + ajax, I encountered an issue where no values were displayed. Although there were no errors when reviewing the console lo ...

Is it possible to use a server action in Next.js to both retrieve data and refresh the page?

I am currently working on developing a web application using Next.js (13.4.9) and I intend to utilize server actions. These server actions will involve sending data to the server, which will process the data and return a string back to me. The challenge I& ...

Browser stores cached data for images even after they have been removed and then re-added

Our team is currently working on a web application that relies solely on AJAX and Javascript for its interface. One challenge we have encountered involves dynamic images with cache expiration times set to access time plus 15 minutes. Typically, when these ...

Lottie-web experiences a memory leak

Currently implementing lottie web on my front-end, but encountering persistent memory leaks. The JavaScript VM instance remains below 10MB when lottie is removed altogether. However, upon enabling lottie, the memory usage escalates rapidly whenever the pa ...

How can I strip out HTML attributes from a String?

Looking for a solution to remove specific id attributes from an HTML string? Here's the scenario: <div id="demo_..." class="menu"> You have the HTML code as a string and want to remove all id attributes starting with demo_. The desired result ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

Efficiently making JQuery Ajax requests using HTTP Basic Authentication

I am currently experiencing challenges with implementing HTTP Basic Authentication in JQuery when communicating with a REST-based server. This server provides responses in both XML and JSON formats, but I have chosen to work with JSON format. Our authoriz ...