My Development Notes

Programming Made Easier


How to return highest and lowest numbers from a list in JavaScript?

Question :

We are given a string of space-separated numbers and we need to return the highest and lowest numbers like so:

highestAndLowest('90 -3 -2 6 70')
//should return highest:90 and lowest:-3

highestAndLowest('1 2 3 4 5 6')
//should return highest:6 and lowest:1

Solution 1

function highestAndLowest(numbers) {
  numbers = numbers.split(" ").map(Number);
  const max = Math.max(...numbers);
  const min = Math.min(...numbers);
  return `highest:${max} lowest:${min}`;
}

console.log(highestAndLowest("90 -3 -2 6 70"));
// outputs highest:90 lowest:-3

We’ve written a function and first used split since the input numbers are in ‘strings’ format and then map() method to create new array to map through each of them. Next, using Math.max and Math.min we return the highest and lowest numbers.

Solution 2

function highestAndLowest(numbers) {
  numbers = numbers.split(" ");

  return `highest:${Math.max(...numbers)} ${" "} lowest:${Math.min(
    ...numbers
  )}`;
}

console.log(highestAndLowest("1 2 3 5 7"));
// output: highest:7 lowest:1

Math.max and Math.min is returned inside back-ticks(“) as shown in the above code block.

Solution 3

function highestAndLowest(numbers) {
  numbers = numbers.split(' ').map(Number);
// split and map through first
  
  var min = Math.min.apply(null, numbers);
  var max = Math.max.apply(null, numbers);
// using .apply method
  
  return max + ' ' + min;
}

console.log(highestAndLowest("1 3 -3 4 0 7"));
//output: 7 -3

Here we’ve used the apply method and only the default parameters (null and numbers) to get the output.

Solution 4

function highestAndLowest(numbers) {
  var arr = numbers.split(" ").sort(function (first, second) {
    return first - second;
  });
  return arr[arr.length - 1] + " " + arr[0];
}

console.log(highestAndLowest("1 3 7 -8"));
//outputs 7 -8

We’re not using Math.max or Math.min here. We’re first sorting the function in such a way that it returns the difference between the present(first) and its previous number and then arranges them accordingly from lowest to the highest using sort method. Then we return the highest and the lowest numbers in the next line of code.


Posted

in

by

Tags:

Leave a Reply