Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  110] [ 2]  / answers: 1 / hits: 19154  / 9 Years ago, thu, june 18, 2015, 12:00:00

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();
}

More From » numbers

 Answers
33

You can use Math.min and Math.max, and use them in an array to return the result, try:





function highestAndLowest(numbers){
numbers = numbers.split( );
return Math.max.apply(null, numbers) + + Math.min.apply(null, numbers)
}

document.write(highestAndLowest(1 2 3 4 5))




[#66152] Wednesday, June 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;