Check if the array contains anything other than zero in javascript?

I have an array that will most likely look like this:

[null, null, null, null, null] 

sometimes this array can change to something like:

 ["helloworld", null, null, null, null] 

I know that I could use a for loop to do this, but is there a way to use indexOf to verify that something in the array is not null.

I am looking for something like:

 var index = indexof(!null); 
+5
source share
4 answers

Use some , which returns a boolean:

 var arr = [null, 2, null, null]; var otherThanNull = arr.some(function (el) { return el !== null; }); // true 

Demo

+15
source

In recent versions of Chrome, Safari, and Firefox (and future versions of other browsers), you can use findIndex() to find the index of the first non-empty element.

 var arr = [null, null, "not null", null]; var first = arr.findIndex( function(el) { return (el !== null); } ); console.log(first); 

(for other browsers there is a polyfill for findIndex() )

+3
source

You can use Array.prototype.some to check if there are any elements matching the function:

 var array = [null, null, 2, null]; var hasValue = array.some(function(value) { return value !== null; }); document.write('Has Value? ' + hasValue); 

If you need the first index of a non-empty element, you will have to do a little harder. First, map each element to true / false, and then get indexOf true:

 var array = [null, null, 2, null, 3]; var index = array .map(function(value) { return value !== null }) .indexOf(true); document.write('Non-Null Index Is: ' + index); 
+2
source

It does the job

 var array = ['hello',null,null]; var array2 = [null,null,null]; $.each(array, function(i, v){ if(!(v == null)) alert('Contains data'); }) 
0
source

Source: https://habr.com/ru/post/955849/


All Articles