I'm practicing my JavaScript and been working on doing little bits of Code Wars. What I'm currently working on is here:
https://www.codewars.com/kata/554b4ac871d6813a03000035/train/javascript
So, my logic was to convert the string of numbers into an array of numbers (calling it input in this instance). Assign the lower and higher values to the input[0] and then for loop through checking whether input[i] was either less or more than the current value of the higher or lower value.
This however has caused errors to occur. I cannot seem to understand why JavaScript is occasionally assigning values incorrectly. Code Wars gives a test example into the function as: ("8 3 -5 42 -1 0 0 -9 4 7 4 -4")
The lowest variable does become -5, but will finish at -1, While my highest variable stays at 8.
Can anyone clue me into where I'm going wrong? I am aware there are probably better methods to do this, that's not what I really want to know. But I don't understand how 8 can be considered larger than 42? Especially as I'm directly comparing them with a logical operator.
I did decide to look at the comparisons via several console.log's but removed these for readers. I also looked at doing one at a time and this didn't help either.
Thank you
Here's my code:
function highAndLow(input){
const numbers = input.split(' ')
parseInt(numbers)
var lowest;
var highest;
if(numbers.length === 1){
return `${numbers[0]} ${numbers[0]}`
} else {
if(numbers[0] > numbers[1]){
lowest = numbers[1]
highest = numbers[0]
} else {
lowest = numbers[0]
highest = numbers[1]
}
for(let i = 0; i < numbers.length; i++){
if(numbers[i] > highest){
highest = numbers[i]
} else if (numbers[i] < lowest){
lowest = numbers[i]
} else {
console.log("Values remain same")
}
}
}
return `Answer is ${highest} ${lowest}`
}
console.log(highAndLow('8 3 -5 42 -1 0 0 -9 4 7 4 -4'))