22

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);
2
  • 2
    Why should you even have an array of null elements? There's no way to do it without iterating (or recursively searching), unless you have an nonderministic machine that guesses always the correct answer, yes or no. Commented Dec 1, 2015 at 22:50
  • Well I'm making a website where you can select out of 5 league of legends champs and if they don't select a champ then the array will stay at null. I tried the for loop method but it didn't seem to work Commented Dec 1, 2015 at 23:07

5 Answers 5

48

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));

Sign up to request clarification or add additional context in comments.

Comments

4

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())

2 Comments

Note, none of the IE browsers support findIndex, not just "older" browsers (IE 11 is still considered "new").
@TbWill4321 True. But the polyfill works fine there.
2

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);

Comments

2

If you just wanna check if there is any non-falsy value in the array, do

arr.some(el => !!el)

Comments

0

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');
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.