I am new to JS. I want to include all the unavailable objects of Value
while filtering. In the code below, I am applying the condition Value >= 4 && Value < 6
. I want (Value >= 4 && Value < 6) || unavailable values of
Value`
var Annual = [{"Date":1998,"Value":6.5,"GDPAnn":9062800},{"Date":1999,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"GDPAnn":10581900}]
result = Annual.filter(function(v) { return v.Value >= 4 && v.Value < 6; })
console.log(result);
Add a !v.Value
condition to your boolean expression
var Annual = [{"Date":1998,"Value":6.5,"GDPAnn":9062800},{"Date":1999,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"GDPAnn":10581900}]
result = Annual.filter(function(v) { return (v.Value >= 4 && v.Value < 6) || !v.Value; })
console.log(result);
Edit:
Like said in a comment below, in a case that you would not to consider that any falsy value is invalid (like zero, empty string, etc), you might prefer using the Object.prototype.hasOwnProperty
method.
const Annual = [{"Date":1998,"Value":6.5,"GDPAnn":9062800},{"Date":1999,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"GDPAnn":10581900}]
const result = Annual.filter(function(v) {
return (v.Value >= 4 && v.Value < 6) || !v.hasOwnProperty("Value");
})
console.log(result);
typeof
check if value undefined make the job too.
const Annual = [{"Date":1998,"Value":6.5,"GDPAnn":9062800},{"Date":1999,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"GDPAnn":10581900}]
result = Annual.filter((v) => v.Value >= 4 && v.Value < 6 || typeof v.Value === "undefined");
console.log('res',result);
use hasOwnProperty
method to check if the object has a property called Value
and negate it.
var Annual = [{"Date":1998,"Value":6.5,"GDPAnn":9062800},{"Date":1999,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"GDPAnn":10581900}]
result = Annual.filter(function(v) { return (v.Value >= 4 && v.Value < 6) || !v.hasOwnProperty('Value') })
console.log(result);