Hi I have an array like: [null,null,null,null] in javascript. How can I know if the array has all values equal to null without iterating over it?
2 Answers
There is no way to check for all null values, you would have to iterate over it, or the function you call will have to in the background. However, if you want, you could use the native Array method filter to help you out.
var allNull = !arr.filter(Boolean).length;
This will work with any falsy value, like undefined, zero, NaN, or an empty string. A more precise form is
var allNull = !arr.filter(function(elem){ return elem !== null; }).length;
Which would check for only null.
Another possibility is using .join:
var allNull = !arr.join("").length;
This checks for null, undefined, or ""
Comments
There are various built–in methods to help, one is every to test that every value isn't null. It will return false at the first null:
var noNulls = array.every(function(value){return value !== null});
Another is some, which will return true at the first null:
var hasNulls = array.some(function(value){return value === null});
1 Comment
every is indeed a helpful method. I didn't even remember it existed.
for(var i = 0; i < arr.length; i++) if(array[i] !== null) allNull = false;