Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the greatest and smallest number in a space separated string of numbers using JavaScript
We are required to write a JavaScript function that takes in a string containing numbers separated by spaces and returns a string with only the greatest and smallest numbers separated by a space.
Problem Statement
Given a space-separated string of numbers, find the maximum and minimum values and return them as a formatted string.
Input:
'5 57 23 23 7 2 78 6'
Expected Output:
'78 2'
Because 78 is the greatest and 2 is the smallest number in the string.
Using Array.reduce() Method
The most efficient approach uses reduce() to iterate through the array once and track both maximum and minimum values:
const str = '5 57 23 23 7 2 78 6';
const pickGreatestAndSmallest = (str = '') => {
const strArr = str.split(' ');
let creds = strArr.reduce((acc, val) => {
let { greatest, smallest } = acc;
greatest = Math.max(val, greatest);
smallest = Math.min(val, smallest);
return { greatest, smallest };
}, {
greatest: -Infinity,
smallest: Infinity
});
return `${creds.greatest} ${creds.smallest}`;
};
console.log(pickGreatestAndSmallest(str));
78 2
Using Math.max() and Math.min() with Spread Operator
A more concise approach uses the spread operator with Math.max() and Math.min():
const str = '5 57 23 23 7 2 78 6';
const findMinMax = (str) => {
const numbers = str.split(' ').map(Number);
const max = Math.max(...numbers);
const min = Math.min(...numbers);
return `${max} ${min}`;
};
console.log(findMinMax(str));
78 2
Using Simple Loop Approach
For better readability, you can use a simple for loop:
const str = '5 57 23 23 7 2 78 6';
const findGreatestSmallest = (str) => {
const numbers = str.split(' ').map(Number);
let max = numbers[0];
let min = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > max) max = numbers[i];
if (numbers[i] < min) min = numbers[i];
}
return `${max} ${min}`;
};
console.log(findGreatestSmallest(str));
78 2
Comparison of Methods
| Method | Performance | Readability | Code Length |
|---|---|---|---|
| Array.reduce() | Good | Medium | Long |
| Math.max/min with spread | Good | High | Short |
| Simple loop | Best | High | Medium |
Key Points
- Always convert string values to numbers using
Number()ormap(Number) - The spread operator approach is most concise for small arrays
- For large datasets, the loop approach offers better performance
- Handle edge cases like empty strings or invalid input
Conclusion
The spread operator with Math.max() and Math.min() provides the cleanest solution for finding greatest and smallest numbers in a space-separated string. Choose the approach based on your performance requirements and code readability preferences.
