'Return highest and lowest number in a string of numbers with spaces
Let's say I have a string of numbers separated by spaces and I want to return the highest and lowest number. How could that best be done in JS using a function? Example:
highestAndLowest("1 2 3 4 5"); // return "5 1"
I would like the both numbers to be returned in a string. The lowest number first followed by a space then the highest number.
Here is what I have so far:
function myFunction(str) {
var tst = str.split(" ");
return tst.max();
}
Solution 1:[1]
Below is a code that improves the solution and facilitates global use:
/* Improve the prototype of Array. */
// Max function.
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
// Min function.
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
var stringNumbers = "1 2 3 4 5";
// Convert to array with the numbers.
var arrayNumbers = stringNumbers.split(" ");
// Show the highest and lowest numbers.
alert("Highest number: " + arrayNumbers.max() + "\n Lowest number: " + arrayNumbers.min());
Solution 2:[2]
OK, let's see how we can make a short function using ES6...
You have this string-number:
const num = "1 2 3 4 5";
and you create a function like this in ES6:
const highestAndLowest = nums => {
nums = nums.split(" ");
return `${Math.max(...nums)} ${Math.min(...nums)}`;
}
and use it like this:
highestAndLowest("1 2 3 4 5"); //return "5 1"
Solution 3:[3]
function highAndLow(numbers){
var temp = numbers.split(' ');
temp.sort(function(a,b){return a-b; });
return temp[temp.length-1] + ' ' + temp[0];
}
did a little differently: first split into an array, then sorted ... and returned the last (maximum) element with the first (minimum) element
Solution 4:[4]
function highAndLow(numbers){
numbers = numbers.split(' ');
return ${Math.max(...numbers)} ${Math.min(...numbers)};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Alireza |
| Solution 3 | bazylevnik0 |
| Solution 4 | Motaz Trabelsi |
