- Challenge:
- You are given a string of space-separated numbers and have to return the highest and lowest number.
- Problem:
- Expected: '542 -214', instead got: '6 -214'
- I can't understand why the system thinks 6 is higher than 542. The program works fine when the 6 is removed.
Code:
function highAndLow(numbers){ numbers = numbers.split(" "); var biggest = numbers[0]; for (i = 0; i < numbers.length; i++) { if (numbers[i] > biggest) { biggest = numbers[i]; } } var smallest = numbers[0]; for (i = 0; i < numbers.length; i++) { if (numbers[i] < smallest) { smallest = numbers[i]; } } return biggest + " " + smallest; } console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));
Asked
Active
Viewed 132 times
0

Eme-rald
- 1
- 1
-
2You got an array of strings. You need to cast it to an int. – Mark Baijens May 28 '18 at 14:17
1 Answers
1
This is because it's comparing the numbers as strings instead of as numbers. You'll want to convert them to numbers using the Number()
function to convert them to numbers before you compare them, for example:
biggest = Number(numbers[0]);

Matthew Schlachter
- 3,250
- 1
- 12
- 26
-
2We don't need **yet another** answer to this question. This is an often-posted duplicate. – T.J. Crowder May 28 '18 at 14:18