Check if an array contains something other than null in javascript?
If you just wanna check if there is any non-falsy valye in the array, do
arr.some(el => !!el)
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);
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()
)
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));