Reputation: 1127
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);
Upvotes: 22
Views: 43482
Reputation: 2696
If you just wanna check if there is any non-falsy value in the array, do
arr.some(el => !!el)
Upvotes: 2
Reputation: 63514
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));
Upvotes: 48
Reputation: 36438
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-null element.
var arr = [null, null, "not null", null];
var first = arr.findIndex(
function(el) {
return (el !== null);
}
);
console.log(first);
(for other browsers, there's a polyfill for findIndex()
)
Upvotes: 4
Reputation: 339
This does the work
var array = ['hello',null,null];
var array2 = [null,null,null];
$.each(array, function(i, v){
if(!(v == null)) alert('Contains data');
})
Upvotes: 0
Reputation: 8666
You can use Array.prototype.some
to check if there are any elements matching a function:
var array = [null, null, 2, null];
var hasValue = array.some(function(value) {
return value !== null;
});
document.write('Has Value? ' + hasValue);
If you want the first index of a non-null element, you'll have to get a bit trickier. First, map each element to true / false, then get the 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);
Upvotes: 2