user1943020
user1943020

Reputation:

How can I loop through an array object and check each element to see if one is defined?

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?

Upvotes: 0

Views: 120

Answers (4)

Kei Minagawa
Kei Minagawa

Reputation: 4521

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

Upvotes: 0

giannis christofakis
giannis christofakis

Reputation: 8321

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?

Upvotes: 1

exacs
exacs

Reputation: 29

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

Upvotes: 0

Remento
Remento

Reputation: 927

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

Upvotes: 2

Related Questions