JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if an array contains only zeros in JavaScript?

To check if an array contains only zeros, go through the following steps:

  1. First, call the array every() method.
  2. Inside the callback function of the every() method, compare each element with zero.
  3. Return true if an element is equal to zero; otherwise, return false.
  4. Lastly, check the value returned by the every() method. If the array contains only zeros, the every() method will return true.

In this way, you can check if all elements in an array are zeros.

let arr1 = [0, 0, 0];
let arr2 = [21, null, "JavaScript", 0, 0];

let result;
result = arr1.every(element => element === 0);
if(result === true)
  console.log('Array arr1 contains only zeros.');
else
  console.log('Array arr1 contains elements other than zero.');

result = arr2.every(element => element === 0);
if(result === true)
  console.log('Array arr2 contains only zeros.');
else
  console.log('Array arr2 contains elements other than zero.');

Output

"Array arr1 contains only zeros."
"Array arr2 contains elements other than zero."

The array every() method is one of the iteration methods. It does not modify the original array.

The every() method accepts a callback function that is called for each array element. You specify the condition within the callback function. The every() method returns true if all the array elements satisfy the condition; otherwise returns false.

array.every((element)=>{
  if(condition){
    return true;
  }else{
    return false;
  }
})

An alternative approach to check if an array contains only zeros is to use for...of loop. In each iteration, compare each array element with zero. If an element is not equal to zero, set the flag to 1 and break the loop.

let arr1 = [0, 0, 0];
let arr2 = [21, null, "JavaScript", 0, 0];

let flag = 0;
for(let element of arr1){
  if(element !== 0){
    flag=1;
    break;
  }
}
if(flag === 0){
  console.log('Array arr1 contains only zeros.');
}else{
  console.log('Array arr1 contains elements other than zero.');
}

flag=0;

for(let element of arr2){
  if(element !== 0){
    flag=1;
    break;
  }
}
if(flag === 0){
  console.log('Array arr2 contains only zeros.');
}else{
  console.log('Array arr2 contains elements other than zero.');
}

Recommended Posts