I have an array defined like this:
var numbers = [11, 12, 13, 14, 15, 16, 17, 18];
I want to check if all numbers in this array are greater 10 and I only want a single output.
I tried this:
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > 10) {
console.log("Valid");
} else {
console.log("Not valid");
}
}
This gives me multiple outputs, since it is inside the loop, but I just want a single valid statement.
PS: Sorry about this noob question.
I personally prefer Array.prototype.every()
.
This function executes a provided callback once for each element until the callback returns false
. If this happens, the every()
function will return false
.
Here is an example:
var numbers = [11, 12, 13, 14, 15, 16, 17, 18];
function checkElements(element, index, array) {
return (element > 10);
}
if (numbers.every(checkElements)) console.log('Valid');
else console.log('Not valid');
Read more about the every() function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With