Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array contains something other than null in javascript?

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);
like image 288
mre12345 Avatar asked Dec 01 '15 22:12

mre12345


People also ask

How do you check if all the elements in an array are not 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 .

How do you check if an array contains a specific value in JavaScript?

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.

How check array is null or not in JavaScript?

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.

How do you check if an array of object contains a value?

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.


1 Answers

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));
like image 57
Andy Avatar answered Sep 19 '22 16:09

Andy