My task is to return the maximum and minimum in the string. Everything would work, but this string, not an array. How can I convert one to another? Help. Or there is another solution about which I do not know, here is my option for the array:

var numbers = [5, 6, 2, 3, 7]; var max = Math.max.apply(null, numbers); var min = Math.min.apply(null, numbers); alert(min); alert(max); 

UPD: example string:

highAndLow ("1 2 3 4 5"); // should return the string "5 1"

those. I can't write a function:

 function highAndLow(numbers){ // ... } 
  • one
    "but this line," - it would be useful to include an example of such a line in the question. - Igor

4 answers 4

You just need to use the function String.prototype.split() , which splits the string into an array according to the specified "delimiter" (in your case, space).

Those. to form an array from the string "1 2 3 4 5" , call:

 var numbers = "1 2 3 4 5".split(" "); // ["1", "2", "3", "4", "5"] var max = Math.max.apply(null, numbers); // 5 var min = Math.min.apply(null, numbers); // 1 

The elements of the array will be strings, but using Math.min and Math.max will be converted to numbers.

    for example

     function highAndLow(s) { var nums = s.split(' ').map(function(x){return +x}); return '' + Math.max.apply(null, nums) + ' ' + Math.min.apply(null, nums); } 

      Based on previous answers:

       function highAndLow(str){ str = str || ''; if(str.length < 2) return str; var nums = str.split(' ').sort(); return nums[0] + ' ' + nums.slice(-1)[0]; }; alert(highAndLow('5 6 2 3 7')); alert(highAndLow('1 2 3 4 5')); alert(highAndLow('')); alert(highAndLow(null)); alert(highAndLow(undefined)); 

      Sort and return the first and last element.

      Update
      Replaced str = str.split(' ').sort();
      on var nums = str.split(' ').sort();

      • sort changes the original array - the assignment line can be removed - Grundy
      • one
        @Grundy, str , we initially have a string, and after the split already an array - hardsky
      • @Grundy but I really forgot about sort :) - hardsky
      • @hardsky clarify please about what you say? The line with the assignment that can be removed is it: - str = str.split ('') .sort (); Why not remove it? - spectre_it
      • @ stas0k, but we are talking about this line. Up to this point, str is a string, and then an array. - hardsky

      function to find the minimum and maximum value in a row of numbers:

       function highAndLow(numbers){ numbers = numbers.split(' ').map(Number); return Math.max.apply(0, numbers) + ' ' + Math.min.apply(0, numbers); } alert(highAndLow('1 2 3 4 5 6 7'));