Find the smallest number within an array without relying on the Math function

Could someone assist me in creating a function that finds the lowest number in an array? I've been struggling with this and previous answers on similar questions didn't really help as they presented solutions with unfamiliar code. The current code I have only returns "0" instead of the expected value of 80. Can anyone provide guidance on how to fix this issue?


                    var numbers = [100, 90, 100, 80];

                    function findLowestNumber(arr) {
                        let lowestNum = arr[0];
                        for (let i = 1; i < arr.length; i++) {
                            if (arr[i] < lowestNum) {
                                lowestNum = arr[i];
                            }
                        }
                        return lowestNum;
                    }

                    console.log(findLowestNumber(numbers));
                
            

Answer №1

While there are existing methods to solve this issue, it appears that the context may involve a homework assignment.

var numbers = [50, 3, 88, -10, 120];

function findLowest(nums) {
  // Assume the first number is the lowest
  var min = nums[0];

  for (var i = 0; i < nums.length; i++) {
    // If current number is lower, update minimum
    if (min > nums[i]) {
      min = nums[i];
    }
  }

  // Result will always be the lowest number in the array
  return min;
}

document.write(findLowest(numbers));

Answer №2

Challenges await;

function findLowestGrade(arr) {
  for (let j = 0; j < arr.length; j++) {
    if (arr[j] < arr.length); // This conditional statement doesn't have any impact
    result = j;  
    {
      return (result);   
    }
  }
}

Try this instead;

var values = [100, 90, 100, 80];
function lowestValue(a) {
  var minVal = a[0];
  for (var k = 0; k < a.length; k++) {
    if (a[k] < minVal) 
       minVal = a[k];
  }
  return minVal;
}

document.write(lowestValue(values));

Answer №3

let grades = [100, 90, 100, 80];

function findLowestGrade(gradesArray) {
    let lowestGrade = gradesArray[0]; 
    for (let i = 1; i < gradesArray.length; i++) { 
        if (gradesArray[i] < lowestGrade)
            lowestGrade = gradesArray[i]; 
    }
    return lowestGrade;
}

document.write(findLowestGrade(grades));

Answer №4

Give this a shot:

let grades = [95, 88, 92, 78];
findLowestGrade(grades);

function findLowestGrade (grades) 
{
    let lowestGrade;
    for(let i = 0; i < grades.length; i++){
        if(typeof lowestGrade === 'undefined') {
            lowestGrade = grades[i]
        } else {
            if(grades[i] < lowestGrade){
                lowestGrade = grades[i];
            }
        }
    }

    console.log(lowestGrade);
}

Check it out on JSFiddle here

Answer №5

As you have specifically requested to avoid using the Math object in Javascript, I came across a solution on Stackoverflow that addresses your query effectively:

function findMax(arr)
{
    var max = -Infinity;
    var index = 0;
    var length = arr.length;

    for (; index != length; ++index) {
        if (arr[index] > max) {
            max = arr[index];
        }
    }

    return max;
}

I want to note that I did not create this solution, so I recommend visiting the original author's response at:

Answer №6

If you're not familiar with sorting techniques, the native reduce function can be used.

let values = [100, 90, 100, 80];
let minVal = values.reduce(function (previousValue,currentValue) {
    return previousValue > currentValue ? currentValue : previousValue;
});
document.write(minVal);

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 keeping MUI Autocomplete open even when the input field loses focus

I am currently working with a MUI autocomplete feature that includes a list of items and an edit icon next to each one. The edit icon allows the user to change the name of the option by rerendering it as a textfield. However, I have encountered an issue wh ...

How can you use yargs (npm package) to generate an error message when a command is not recognized?

Is it possible to have yargs with 2 commands? yargs .command('test-all','',handler) .command('test-file','',handler) .argv When the user inputs: node myapp.js other-command No error is thrown by yargs. What steps s ...

The React Material-UI Slider does not move when OnChangeCommitted is triggered

Struggling with implementing the Material UI slider in React, I encountered an issue where the OnChange function would trigger every time the value changed. I needed it to activate only when the left mouse button was released. Fortunately, I discovered a s ...

Discover the best practices for implementing MongoDB's latest Schema Validation functionality within your Express.js application

Need help implementing MongoDB's Schema Validation in an Express server? While working on a simple todo app, I opted for the native MongoClient over mongoose but still require a schema for my data. According to MongoDB's documentation available ...

Selenium webdriver cannot find the element within the JavaScript code

await driver.findElement(By.id('closeBtn')).click(); or await driver.findElement(By.xpath('//*[@id="closeBtn"]')).click(); When attempting to use the above conditions for a pop-up, it does not work as expected. An error is ...

What causes Jest to throw ReferenceErrors?

Question Does anyone know why I am encountering this error? ● Test suite failed to run ReferenceError: Cannot access 'mockResponseData' before initialization > 1 | const axios = require('axios'); ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

NodeJS hit with ECONNREFUSED error while trying to run localhost server

I currently have a NodeJS server running on my local machine, listening to port 50000. I am trying to make a simple GET request to this server from another local server, but I keep receiving an ECONNREFUSED error message: { Error: connect ECONNREFUSED 127 ...

Embed information from a MySQL database into an HTML layout

I have a main webpage containing various links (e.g. fist_link, second_link, etc...) When a user clicks on any link, it should open blank_template.html. If the user clicks on fist_link, the template should display the first string from the database table. ...

Choose all the items that are visible in the list using Angular

If you have the following ng-repeat: <ul class="list-group"> <ng-user-item ng-repeat="user in users | filter:search" user="user" ng-if="assigned.indexOf(user.id) < 0" ng-click="selectFunction(user);"></ng-use ...

Integrate actual credentials into S3Client using redux async thunk

My S3-like react application with redux is powered by AWS SDK v3 for JS. The client initialization in my auth.js file looks like this: auth.js export const s3Client = new S3Client({ region: 'default', credentials: { accessKeyId: 'te ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...

Server encountered an unexpected T_STRING error that was not present on the localhost

While my website runs smoothly on localhost, I encounter the unexpected T_STRING error when running it on a workplace server with PHP 5.3.3. The culprit seems to be the exportXML function: eliminating this function resolves the issue. Any suggestions? I&a ...

Deactivating elements on a website

Is there a way to prevent multiple transactions due to unintended repeated clicks on a button by disabling all webpage elements when the button is clicked? Suggestions include using a div that can be layered on top of the elements when the button is click ...

Obtaining JSON information with Svelte

I'm currently facing a mental block. My goal is to fetch JSON data using the Youtube API. The error message I am encountering is "Cannot read property 'getJSON' of undefined". Here's the code snippet I have provided: <script> ...

Issue: setAllcategories function not found

Currently engaged in using Next.js and Sanity as a Headless CMS for the backend. In the code snippet below, I have created a Categories.js file in the components folder to fetch some data. My objective is to extract all the titles from the category Array. ...

IE 7 textarea malfunctioning with word spacing issues

I have a website using the LAMP stack with a form that users fill out. Strangely, when I view the submitted form data in IE 7, it adds line breaks between each word. The form is simple with input elements and a text area. Submitting the form in FF3+, IE8, ...

Does Parsley.js offer a way to configure so that the parsley-success field is not added to an input if it should be completely ignored?

Currently, I am excluding one input and adding the success class (which is fine with me) $('form').parsley({ excluded: '[data-parsley-sum-total="all"]' }); However, there are several other inputs without any validations that I do not wa ...

Total number of requests made since the previous reset

I'm currently working on developing an API and I need to set up a route like api/v1/status in order to check the server status. This route should return a JSON response with the total number of requests made to the API since it became active. However, ...

What is the best way to maintain the toggleClass event state once an ajax call has been made?

If I have the HTML code below <div class="row"> <div class="link grey"> <a href="#">Link</a> </div> </div> <div class="row"> <div class="link"> <a href="#">Link</a> </div> & ...