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.

2

6 Answers

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 loop

If 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 

RegExp

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

2

Using ECMA5 every

function zeroTest(element) { return element === 0; } var array = [0, 0, 0, 0]; var allZeros = array.every(zeroTest); console.log(allZeros); array = [0, 0, 0, 1]; allZeros = array.every(zeroTest); console.log(allZeros);
1

Use an early return instead of 2, 3 jumps. This will reduce the complexity. Also we can avoid initialisation of a temp variable.

function ifAnyNonZero (array) { for(var i = 0; i < array.length; ++i) { if(array[i] !== 0) { return true; } } return false; } 

you can give a try to this :

var arr = [0,0,0,0,0]; arr = arr.filter(function(n) {return n;}); if(arr.length>0) console.log('Non Zero'); else console.log("All Zero"); 

No need to loop, simple join and reg expression will work.

var arr = [0,0,0,10,0]; if((/[^0]/).exec(arr.join(""))){ console.log("non zero"); } else { console.log("I am full of zeros!"); } 

Another slow way of doing it, but just for fun.

var arr = [0,0,0,0,10,0,0]; var temp = arr.slice(0).sort(); var isAllZeros = temp[0]===0 && temp[temp.length-1]===0; 
6

Using Math.max when you know for certain that no negative values will be present in the array:

const zeros = [0, 0, 0, 0]; Math.max(...zeros) === 0; // true 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy