Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements