What is the best way to save a user input in an array and then find its maximum and minimum values?

I am currently working on a script that involves taking values from a prompt, converting them to integers, storing them in an array, and then finding the minimum and maximum values within that array. I am unsure whether I should convert the user input to integers or the array items themselves. Additionally, I need a method to split the array into individual elements based on the user's input size. For instance, if a user enters "1 2 10 40" into the prompt, they should receive an alert indicating the minimum value is 1, the maximum value is 40, and the array length is 4. Below is snippet of the code I am experimenting with:

var numInput = prompt("Enter a series of numbers with spaces in between each:");
var numArray = [];
numArray.push(numInput);
numInput.split(" ");
alert(Math.min(numArray));
alert(Math.max(numArray));

Answer №1

In order to properly utilize the .split method, you must assign its result to an array variable.

Math.min and Math.max functions require separate numbers as arguments, not an array of numbers. To achieve this, you can use the apply method to spread the array elements into individual arguments.

var numInput = prompt("Please enter a series of numbers separated by spaces:");
var numArray = numInput.split(" ");

alert(Math.min.apply(null, numArray));
alert(Math.max.apply(null, numArray));

Answer №2

When you break down the string, it's important to identify the smallest and largest values.

let numbers = prompt("Type a sequence of numbers separated by spaces:");
let numArray = numbers.split(" ");
let max = Number.MIN_VALUE;
let min = Number.MAX_VALUE;
for(let i=0; i<numArray.length; i++){
  if(parseInt(numArray[i])<min)
    min=parseInt(numArray[i]);
  if(parseInt(numArray[i])>max)
     max=parseInt(numArray[i]);
}
alert(min);
alert(max);

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

Update the jQuery Get function to enable asynchronous behavior

I've recently been tasked with updating some older code to be asynchronous. The code in question is a jQuery GET function that looks like this: jQuery.get("my url", function(data){ //code here }); What steps can I take to convert this to an as ...

Three.js Morph Targets: A Deep Dive

I'm diving into the world of morph targets and three.js, but I'm struggling to find comprehensive documentation on this topic. Upon reviewing the source code, it seems like morphTargetInfluences[] is the key element. Can someone explain how thi ...

What is the best approach for selecting and organizing MongoDB records, as well as identifying the following record for retrieval?

Currently, I have a stack of documents that needs to be filtered out based on specific criteria and then arranged alphabetically according to the string value within those documents — let's call it a "search result". Subsequently, I am required to l ...

How should values be properly stored in a constant using mongoose?

Within my user model, I have included timestamps. I am seeking a way to retrieve the createdAt date and store it in a variable. My initial attempt was: const date = await User.find({ serial: serialId, }).select('-_id createdAt'); The result re ...

Creating a bot with discord.js to dynamically edit embed messages

While using discord.js version 12+, I encountered an error when trying to edit an embed sent by the bot. The error message displayed is as follows: Uncaught Promise Error: DiscordAPIError: Cannot edit a message authored by another user at RequestHand ...

Guide to including a class within an "else" statement in JavaScript

function check_empty() { if (document.getElementById('CompanyName').value == "" || document.getElementById('ContactName').value == "" || document.getElementById('Address').value == "" || document.getElementById('PhoneNumb ...

Preventing Parent CSS from Affecting Child Component CSS

I designed a React app that serves as a widget for easy inclusion on any HTML page. Unfortunately, I noticed that the CSS of this React app is being influenced by the CSS of the parent page it's placed in. I have a well-defined index.scss file where I ...

Setting the outcome of an Ajax call as a global variable in JavaScript

I have a method that uses AJAX to request data and returns a JSON string containing Tokens records. I am trying to store this result in a global variable named 'tokens' so I can access it in other functions. After assigning the result to the &ap ...

What is the best way to ensure that the texture is properly positioned when replacing textures in gltf format using Three.js?

Trying to dynamically change the texture of a glTF model using the `THREE.TextureLoader`, I successfully changed the color as expected. However, the texture pattern appeared distorted. Exploring web graphics for the first time, I modified a 3D model viewe ...

Issue: Configuration Error - CKEditor5 cannot be loaded for extension in Vuejs

Hey everyone, I'm currently facing an issue. I'm trying to customize a build and everything works fine in the cloned ckeditor along with the sample.html file. However, when attempting to implement the customized build in Vue 2, I encounter an err ...

What is the method for handling JSON data in Node.JS?

I am working with a Node.JS file that includes the following code: var express = require('express'); var app = express(); var http = require('http').Server(app); var cfenv = require("cfenv"); var appEnv = cfenv.getAppEnv(); http.list ...

Optimizing the performance of ajax calls using the

I'm currently using the setInterval method to execute AJAX in order to fetch data from a database in real time (every second). At the moment, I am only pulling small amounts of data from the meeting_minutes_queries.php, which is not causing any delays ...

Issue with running JavaScript functions on HTML elements in a partial when updating it with AJAX in ASP.NET MVC Core

My asp.net mvc core 2.2 application includes a page where a partial is loaded: <div class="col-md-9" id="content"> @await Html.PartialAsync("_TrainingContent") </div> The partial contains a model and loads a video using the video.js playe ...

Angular lacks the ability to directly set HTTP headers, except when using an interceptor

When utilizing an HTTP interceptor to include an authentication token in all requests, I encountered a scenario where I needed to add a different token instead of the standard auth token for a specific request. The challenge I faced was the inability to se ...

ReactJS issue: Violation of the Invariant

I have recently started working on an exciting project using React JS and I have been enjoying the process so far. However, I recently encountered an error that has been causing me some trouble. Here is the error message I received: Uncaught Error: Invari ...

Having trouble with Next.js environment variables not being recognized in an axios patch request

Struggling with passing environment variables in Axios patch request const axios = require("axios"); export const handleSubmit = async (formValue, uniquePageName) => { await axios .patch(process.env.INTERNAL_RETAILER_CONFIG_UPDATE, formVal ...

Raphael and jQuery/JavaScript for user-selected array intersections

Hello everyone! This is my first time posting here, and I must say that I'm still quite new to JavaScript/jQuery/Raphael. Please forgive me if I make any mistakes or ask basic questions. :) I've been searching high and low for answers to my quer ...

Incorporate an array into a JSON object using AngularJS

I'm attempting to append a JSON array to a JSON object. Here's my code: $scope.packageElement = { "settings": [ { "showNextPallet": true, "isParcelData": false, "isFreightData": true, " ...

What is the best way to achieve a stylish Bootstrap modal design with a blurred and transparent header, as well as a left sidebar that seamlessly blends into

Is it feasible to create a modal with a blurred (transparent) background for the header section, allowing the site to show through? Additionally, can a sidebar on the left side of the modal also be transparent and blurred, revealing the site underneath? C ...

What's in Meteor 1.3? Discover the best practices for declaring your helpers!

As I navigate through Meteor 1.3's include logic, I find myself facing a challenge. In an app that I am currently piecing together, my /client/main.js file contains: import '../imports/startup/accounts-config.js'; import '../imports/u ...