0

I have an array object that looks like this:

var myArr = [undefined, undefined, undefined, undefined, undefined];

How can I loop through the array object and call a function if any one of the elements in the array is defined and not null?

1
  • Do you mean "defined" in the sense of the Array member exists, or "defined" in the sense of "exists, and not undefined"? You also then say "not null", so are you saying you also want a null check? Commented Mar 22, 2014 at 15:07

4 Answers 4

2

If you don't care what the valid value is:

var myFunction = function(){console.log("array has valid values");};
var myArr = [undefined, undefined, undefined, undefined, 2];
var hasUndefined = myArr.some(function(item){
    return typeof item !== "undefined";
});
if (hasUndefined){
    myFunction();
}

If you need to find out what the valid items are:

var myFunction = function(validItems){
    console.log("array has valid values, and here they are:",validItems);
};
var myArr = [undefined, undefined, undefined, undefined, 2];
var validItems = myArr.filter(function(item){return typeof item !== "undefined";})
if (validItems.length){
    myFunction(validItems);
}
Sign up to request clarification or add additional context in comments.

Comments

1
var myArr = [null,undefined,4,5];

for (var i in myArr) {
    if (myArr[i]) {
        //Do something..
        return;
    }
}

I've also seen this which seems a very nice way.

[null,undefined,4,5].every(function(e) {
    if (e) {
        //Do something..
        return false;
    }
    else return true;
});

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

3 Comments

He wants to avoid null as well and forEach will make the function to be executed for every valid element.
You are right I think I misinterpret what he want. But I think !== avoids null although I must check.
Even return will not help.
0

Try this

function isNotUndefined(item) {
    return typeof item != "undefined";
}

if (myArr.some(isNotUndefined)) {
   //do something
}

In this code I use the Array.prototype.some function to check if any element is defined (to do this I use an extra function called isNotUndefined).

1 Comment

Doesn't work for me, although it seems a very nice way.
0

Try this.

var myArr = [undefined, null, 123, undefined, null, 456];//for test
myArrFilterd = myArr.filter(function(x){return x!=null?true:false;});
myArrFilterd.forEach(function(x){console.log(x);/*something you want to do for each element*/});

output:

123
456

Comments

Your Answer

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