Finding the greatest and smallest number in a space separated string of numbers using JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 17-Apr-2021 11:51:28
Advertisements