Make a function that takes a string with numbers and returns the highest and lowest value

Asked

Viewed 118 times

0

Your function will receive a string as parameter. Separate this string using the ' ' character and return a string containing the largest number and the smallest number (necessarily in this order).

function  maiorEMenor(numbers) {

    var numeros = [];

      for (let i = 0; i < numbers.length; i +=2) {
        numeros.push(parseInt(numbers.substr(i, i+1)))
      }
  
      var maior = Math.max.apply(null, numeros)
      var menor = Math.min.apply(null, numeros)
      
      return maior.toString() + ' ' + menor.toString()
 
}

The code works unless the parameter starts with negative numbers or is only a number.

Example: if the input is '1 2 3 4 5' it returns '5 1';
but if the input is '42' it returns '4 2' instead of '42 42' and with negative entries it gets returns Nan

  • Substr is selected 1 Character at a time, tries with String split

1 answer

0

Reducing your current code, everything gets easier using split.

function maiorEMenor(numbers) {

    const e_num = numbers.split(" ");

    let maior = Math.max.apply(null, e_num)
    let menor = Math.min.apply(null, e_num)
  
    return maior.toString() + ' <= maior : menor => ' + menor.toString()
 
}
console.log(maiorEMenor("4 5 6"));

Resultado

I hope that’s what you’re looking for.

  • In the exercise it is to be only a parameter, type "4 5 6" and I could not use the split to do this

  • be clearer! because in the example there is already a single parameter passing the values 4,5,6. Ex: maiorEMenor("4 5 6");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.