Return highest and lowest number in a string of numbers with spaces

后端 未结 4 1874
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 14:14

Let\'s say I have a string of numbers separated by spaces and I want to return the highest and lowest number. How could that best be done in JS using a function? Example:

4条回答
  •  孤街浪徒
    2021-01-03 14:43

    OK, let's see how we can make a short function using ES6...

    You have this string-number:

    const num = "1 2 3 4 5";
    

    and you create a function like this in ES6:

    const highestAndLowest = nums => {
      nums = nums.split(" ");
      return `${Math.max(...nums)} ${Math.min(...nums)}`;
    }
    

    and use it like this:

    highestAndLowest("1 2 3 4 5"); //return "5 1"
    

提交回复
热议问题