Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if all elements of an array are null?

What's the best way to check for an array with all null values besides using Lodash, possibly with ES6?

var emp = [null, null, null];
if (_.compact(emp).length == 0) {
  ...
}
like image 909
MegaChan Avatar asked Jun 28 '17 22:06

MegaChan


People also ask

How do you check if all the values in an array are null?

To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to null . Copied!

How do you check if an array is empty or null?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.

How do you check if all elements in an array are zero JavaScript?

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);


1 Answers

A side note: Your solution doesn't actually check for an all-null array. It just checks for an all-falsey array. [0, false, ''] would still pass the check.

You could use the Array#every method to check that every element of an array meets a certain condition:

const arr = [null, null, null];
console.log(arr.every(element => element === null));

every takes a callback in which the first argument is the current element being iterated over. The callback returns true if the element is null, and false if it is not. If, for all the elements, the callback returns true, it will evaluate to true, thus if all elements in the array are null, it's true.

like image 193
Andrew Li Avatar answered Oct 14 '22 04:10

Andrew Li