Reputation: 27
Hi I have an array that looks like:
hrarray = [-9,-7,0,3,7,8]
I've been trying to work out a function that selects the first non-negative (inc. 0) number in the array and returns the index (var elemid):
for (var i = 0, len=hrArray.length; i<len; i++) {
var num = hrArray[i];
if(num > 0) {
var elemid = i; //returns first non-negative element index
}
else if(num < 0) {}
Is my code logic correct?
Upvotes: 1
Views: 1411
Reputation: 4400
I don't see you returning anything.
You can get the first non-negative with a single line:
for (var i = 0, len = arr.length; i < len && arr[i] < 0; i++);
Basically, we place the check for negatives in the for-loop guard. It will break once it finds a non-negative and hence return i
of that first non-negative.
Update #1 (to use in a function):
function getFirstNonNegative(arr) {
for (var i = 0, len = arr.length; i < len && arr[i] < 0; i++);
// Use a ternary operator
return (i === len) ? -1 : i; // If i === len then the entire array is negative
}
Upvotes: 1
Reputation: 148980
The main problem I see is that you're not breaking out of the loop once you find a non-negative value. This can be done with a break
statement, or if you want to exit a function immediately, a return
statement.
The function should look a bit like this:
function findNonNegative(arry) {
for (var i = 0, len = arry.length; i < len; i++) {
if(arry[i] >= 0)
return i;
}
return -1;
}
Note that this method returns -1
if no non-negative elements are found.
And with a little tweaking, this can be shortened to:
function findNonNegative(arry) {
for (var i = 0; arry[i] < 0; i++);
return i < arry.length ? i : -1;
}
This version takes advantage of the behavior of the for
loop to both test our values inside the loop and break out once a desired value is found. It also depends on the fact that x < y
always returns false if x
is undefined
, thus ensuring we do not end up with an infinite loop. The last conditional expression is there to make the return value equal -1
if no non-negative elements were found; that can be reduced to just return i;
if you are okay with the return value being arry.length
in that case.
Upvotes: 0
Reputation: 454
Your code will assign to elemid the last non-negative in the array. Try this:
var elemid=-1; // elemid should be declared outside the for statement
for (var i = 0, len=hrArray.length; i<len; i++) {
if(hrArray[i] > 0) {
elemid = i; //returns first non-negative element index
break;
}
}
Upvotes: 0