Reputation: 396
I created an array of integers and wanted to know if it had one or more negative values in it.
I do not want to create a for() loop and check if each element in the array is positive or negative because I only want to return once (ex: I don't want my function to "return false;" a million times).
One option I considered was multiplying each value in the array by the absolute value of its reciprocal, so I get an array of 1s or -1s (or undefined if value is 0) and then I could sum all of the values in this second array to see if it equals the length of the array.
However, the problem with this method is it does not account for 1/0, and also it is tedious. I want to know if there is a faster way to check if an array contains at least one negative value.
--from a beginner JavaScript programmer
Upvotes: 8
Views: 22682
Reputation: 1385
You could leverage Array.prototype.some
which will return true or false if an item in the array matches the given condition. It'll also stop checking remaining values if the condition matches an element:
let values = [1, 4, 6, -10, -83];
let hasNegative = values.some(v => v < 0);
Upvotes: 21
Reputation: 535
This will only return 1 value and break as soon as a negative is found.
function doesArrayContainNegative(array){
//if negative is found return true (breaking loop)
for(var arr of array){
if(arr < 0) return true;
}
//if no elements are negative return false
return false;
}
var array1 = [9, -3, 5, 8]
console.log(doesArrayContainNegative(array1))
Upvotes: 1
Reputation: 1608
What's the issue with the for loop needing to return false all the time?
fucntion containsNegative(myArray)
for(var i = 0; i < myArray.length(); i++)
{
if(myArray[i] < 0){
return true;
}
}
return false;
}
and if you wanted to get the amount of negative numbers
fucntion getNegative(myArray)
var count = 0;
for(var i = 0; i < myArray.length(); i++)
{
if(myArray[i] < 0){
count++
}
}
return count;
}
Upvotes: 0
Reputation: 113
why do you find min value in array? see
JavaScript: min & max Array values?
Math.min(...array)
Upvotes: 2