I have an array that will most likely always look like:
[null, null, null, null, null]
sometimes this array might change to something like:
["helloworld", null, null, null, null]
I know I could use a for loop for this but is there a way to use indexOf
to check if something in an array that is not equal to null.
I am looking for something like:
var index = indexof(!null);
The simplest way to check if all values in array are null is to use the array every() method. The every() method loops through the array and compares each element to null . If all array elements are null, then the every() method will return true ; otherwise, it will return false .
JavaScript Array includes()The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.
isArray() method. This method returns true if the Object passed as a parameter is an array. It also checks for the case if the array is undefined or null. The array can be checked if it is empty by using the array.
Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.
Use some
which returns a boolean:
const arr = [null, 2, null, null];
const arr2 = [null, null, null, null];
function otherThanNull(arr) {
return arr.some(el => el !== null);
}
console.log(otherThanNull(arr));
console.log(otherThanNull(arr2));
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