Sara Keleman
Sara Keleman

Reputation: 23

How to use a for loop to find the greatest number in a string

It should be really simple, but the code I wrote isn't seeming to work no matter how I tweak it

I tried splitting the string into an array and using a for loop to loop through and compare all the numbers but I keep on getting the wrong answer

function highAndLow(numbers){
  // ...
  numbers=numbers.split(" ");
  let lowNum=numbers[0];
  let highNum=numbers[0];

  console.log(numbers)

    for (var i = 1; i < numbers.length; i++) {
        if (numbers[i]>highNum){
            highNum=numbers[i]
        }
    else if(numbers[i]<lowNum){
    lowNum=numbers[i]
    }
}
console.log(highNum)

  return highNum+" "+lowNum
}

highNum keeps returning 6 when it should return 542, and lowNum is acting weird too...

Upvotes: 2

Views: 120

Answers (4)

CrayonViolent
CrayonViolent

Reputation: 32517

As others have mentioned, your immediate issue is strings aren't compared the same as numbers, so you must convert the (string) numbers to actual numbers. Beyond that, here is some shorter code for you.

// String of space delimited numbers
var string = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6";
// Split into an array
var nums = string.split(' ');

// Use built-in Math method which with some nifty ES6 syntax
// Note that Math.max/min automatically convert string args to number
var highNum = Math.max(...nums);
var lowNum = Math.min(...nums);

Upvotes: 2

Chivenh
Chivenh

Reputation: 114

Maybe you try these.

function highAndLow(numbers){

  numbers=numbers.split(" ");
  let lowNum =+ numbers[0];
  let highNum =+ numbers[0];

  console.log(numbers);

  for (var i = 1; i < numbers.length; i++) {
      let num =+ numbers[i];   
      if (num > highNum){
        highNum = num 
      } else if(num < lowNum) {
        lowNum = num
      }
  }

  console.log(highNum)
  return highNum + " " + lowNum
}

Upvotes: 1

Casper
Casper

Reputation: 1539

You can sort() the array and return smallest and largest number. slice() prevents the array itself from being sorted.

var numbers = '4 5 29 54 4 0 -214 542 -64 1 -3 6 -6';
function highAndLow(numbers){
  numbers = numbers.split(" ");
  let sorted = numbers.slice().sort(function(a, b) {
     return a - b;
  });

  let smallest = sorted[0]
  let largest = sorted[sorted.length - 1];

  return smallest + "," + largest 
}

 //call the function
 console.log(highAndLow(numbers))

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You need to parse string into numbers before using comparison, else it will be matches lexicographically as string not as number

console.log("22" > "3")
console.log( "22" > 3)        // implicit conversion to number 
console.log(+"22" > +"3")     // explicitly converted to number 

string comparision

Upvotes: 0

Related Questions