- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the greatest and smallest number in a space separated string of numbers using JavaScript
Problem
We are required to write a JavaScript function that takes in a string that contains numbers separated by spaces.
Our function should return a string that contains only the greatest and the smallest number separated by space.
Input
const str = '5 57 23 23 7 2 78 6';
Output
const output = '78 2';
Because 78 is the greatest and 2 is the smallest.
Example
Following is the code −
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));
Output
78 2
- Related Articles
- Finding the only even or the only odd number in a string of space separated numbers in JavaScript
- Finding difference of greatest and the smallest digit in a number - JavaScript
- Finding smallest number using recursion in JavaScript
- Finding the smallest fitting number in JavaScript
- JavaScript Recursion finding the smallest number?
- Finding second smallest word in a string - JavaScript
- Find the number of whole numbers between the smallest and the greatest number of 2 digits.
- Finding a greatest number in a nested array in JavaScript
- Summing numbers present in a string separated by spaces using JavaScript
- Explain the greatest and the smallest comparing numbers.
- Finding the minimum and maximum value from a string with numbers separated by hyphen in MySQL?
- Finding the number of words in a string JavaScript
- Finding number of spaces in a string JavaScript
- Finding the largest and smallest number in an unsorted array of integers in JavaScript
- Greatest sum and smallest index difference in JavaScript

Advertisements