Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check in JavaScript if all number elements in an array are adequate

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.

like image 870
Meier Avatar asked Dec 25 '22 16:12

Meier


1 Answers

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.

like image 105
Matthias A. Eckhart Avatar answered Dec 27 '22 06:12

Matthias A. Eckhart