Reputation: 2041
Very simple question: I'm trying to compare values in an array and I'm completely stumped as to why my comparison logic is failing. Somehow, during the course of my loop, 6 is being evaluated as > 524. Any ideas as to what I'm doing wrong? I'm totally stumped. Here's the code, and thanks!
function highAndLow(numbers){
var compArr = numbers.split(" ");
var highNum = compArr[0]
var lowNum = compArr[0];
for (i = 1; i < compArr.length; i++) {
if (compArr[i] > highNum) {
highNum = compArr[i]
console.log(highNum)
}
}
for (i = 1; i < compArr.length; i++) {
if (compArr[i] < lowNum) {
lowNum = compArr[i]
}
}
return highNum + " " + lowNum
}
highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")
Again, I'm not sure how, but the result I'm getting in the console is 6 for the highNum (incorrect) and -214 for the lowNum (which is correct). Am I missing something obvious?
Upvotes: 1
Views: 32
Reputation: 2041
edited to include Barmar's answer. Thanks Barmar!
I figured it out. My comparison was running to the edge of the array and trying to compare to undefined. Also, because of the way I had set things up, this method wouldn't work on strings with only two values. Here's my new code:
function highAndLow(numbers){
var compArr = numbers.split(" ").map(Number);
var highNum = compArr[0]
var lowNum = compArr[0];
if (compArr.length === 2) {
if (compArr[1] > highNum) {
highNum = compArr[1]
}
if (compArr[1] < lowNum) {
lowNum = compArr[1]
}
} else {
for (i = 1; i < compArr.length - 2; i++) {
if (compArr[i] > highNum) {
highNum = compArr[i]
}
}
for (i = 1; i < compArr.length - 2; i++) {
if (compArr[i] < lowNum) {
lowNum = compArr[i]
}
}
}
return highNum + " " + lowNum
}
There's probably a better/cleaner way to do this, however.
Upvotes: 0
Reputation: 781096
The elements of compArr
are strings, so they're being compared lexicographically, not numerically. You should make an array of numbers:
var compArr = numbers.split(" ").map(Number);
function highAndLow(numbers){
var compArr = numbers.split(" ").map(Number);
var highNum = compArr[0]
var lowNum = compArr[0];
for (i = 1; i < compArr.length; i++) {
if (compArr[i] > highNum) {
highNum = compArr[i]
console.log(highNum)
}
}
for (i = 1; i < compArr.length; i++) {
if (compArr[i] < lowNum) {
lowNum = compArr[i]
}
}
return highNum + " " + lowNum
}
console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));
Upvotes: 1