I have an array. I need to generate an alert if all the array items are 0. For example,
if myArray = [0,0,0,0];
then alert('all zero');
else
alert('all are not zero');
Thanks.
You can use either Array.prototype.every
or Array.prototype.some
.
Array.prototype.every
With every
, you are going to check every array position and check it to be zero:
const arr = [0,0,0,0];
const isAllZero = arr.every(item => item === 0);
This has the advantage of being very clear and easy to understand, but it needs to iterate over the whole array to return the result.
Array.prototype.some
If, instead, we inverse the question, and we ask "does this array contain anything different than zero?" then we can use some
:
const arr = [0,0,0,0];
const someIsNotZero = arr.some(item => item !== 0);
const isAllZero = !someIsNotZero; // <= this is your result
This has the advantage of not needing to check the whole array, since, as soon it finds a non-zero value, it will instantly return the result.
for
loopIf you don't have access to modern JavaScript, you can use a for
loop:
var isAllZero = true;
for(i = 0; i < myArray.length; ++i) {
if(myArray[i] !== 0) {
isAllZero = false;
break;
}
}
// `isAllZero` contains your result
If you want a non-loop solution, based on the not-working one of @epascarello:
var arr = [0,0,0,"",0],
arrj = arr.join('');
if((/[^0]/).exec(arrj) || arr.length != arrj.length){
alert('all are not zero');
} else {
alert('all zero');
}
This will return "all zero" if the array contains only 0
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