Include unavailable objects in filtering - javascript

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

You can achieve that in different ways.
If falsy value which is 0 is not a valid one then you can use !v.value along with the v.Value >= 4 && v.Value < 6
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(v => (v.Value >= 4 && v.Value < 6) || !v.Value)
console.log(result);
You can use Object.hasOwnProperty() method to check if property exist or not.
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(v => (v.Value >= 4 && v.Value < 6) || !v.hasOwnProperty('Value'))
console.log(result);

Related

Making flags with conditions using Pentaho/JavaScript

I'm trying to optimize my code with a better way to do this.
I have a variable "hour". I need to make flags like this:
if (hour == 0) {flag12AM = 'yes'}
else {flag12AM == 'no'}
if (hour == 0 || hour == 1) {flag1AM = 'yes'}
else {flag1AM == 'no'}
if (hour == 0 || hour == 1 || hour == 2) {flag2AM = 'yes'}
else {flag2AM == 'no'}
[...]
if (hour == 0 || hour == 1 [...] || hour == 23) {flag23PM = 'yes'}
else {flag23PM == 'no'}
Could I use a loop to do that? I'm using Pentaho, so, if there's any step that do this job, please, let me know.
Thanks!!
Maybe this will be useful for you:
var h = 20;
[...Array(24).fill().map((v, i) => i + 1)]
.forEach((v) =>
console.log([...Array(v).fill().map((h, i) => i)]
.reduce((result, currentValue) => result || (h == currentValue), false), v))
You can use a data grid step to generate all flag values and then look up the hour and retrieve all flags.
IIUC, using Modified Java Script Value step, you can calculate all the flags with a for loop and then assign and export the values to specific flag names
var flags = []
for (i=0; i<24; i++) {
flags[i] = hour <= i ? "yes" : "no"
}
var flag12AM = flags[0]
var flag1AM = flags[1]
var flag2AM = flags[2]
....
var flag23PM = flags[23]
Or use Scripting -> Formula step
New field: flag12AM
Formula: IF([hour]<=0;"yes";"no")
Value type: String
do the similar to all other fields.

Improving if-else with multiple values?

Is there a better way to do this?
if(cpf.length !== 11 || cpf === "00000000000" || cpf === "11111111111" ||
cpf === "22222222222" || cpf === "33333333333" || cpf === "44444444444" ||
cpf === "55555555555" || cpf === "66666666666" || cpf === "77777777777" ||
cpf === "88888888888" || cpf === "99999999999"){
You could debate if this is better but this is what I like to do in that sort of situation:
// Name this something relevant to the problem
var possibleValues = ["0000000000", ...];
if (possibleValues.includes(cpf)) {
// do stuff
}
or if you're in an environment that doesn't have includes
if (possibleValues.indexOf(cpf) > -1) {
// do stuff
}
Another possibility is using a regular expression:
if (cpf.length === 11 && cpf.match(/^(\d)\1+$/)) {
// do stuff
}
^: Start at the beginning
(\d): Look for a digit and remember it
\1+: Look for the remembered digit repeatedly
$: Hit the end of the string
Using indexOf Something like
var possibleValues = [ "00000000000", "1111111111" ]; //add more values
if ( cpf.length != 11 || possibleValues.indexOf( cpf ) != -1 )
{
//value matching
}
Alternative Ecmascript5 solution using isNaN() and RegExp.text() functions:
if (cpf.length !== 11 || (!isNaN(f = cpf[0]) && new RegExp("^"+ f + "{11}$").test(cpf))) {
// do something
}
isNaN() - to check if we have only numbers(at start)
new RegExp("^"+ f + "{11}$").test(cpf) - to test if we have a sequence of same 11 digits

How to get the max occurrences of a number in an array

as answer to an exercise in which I had to create a function that given an array of numbers return the number with most occurrences, and if more than one number had the max number of occurrences return the minor one. This is the implementation I made, but I'm pulling my hair figuring out why it return 10 instead of 9 in the example.
It appears to be evaluating 10 < 9 as true. What's wrong?
function maxOccurencies(arr) {
var aux = [], max = 0, final = null;
for (var i=0,t=arr.length; i<t; i++) {
aux[arr[i]] = (aux[arr[i]] || 0) + 1;
if (aux[arr[i]] > max) max = aux[arr[i]];
}
for (x in aux) {
if ( aux[x] == max && (x < final || final == null)) {
final = x;
}
}
return final;
}
document.write(maxOccurencies([10,10,10,9,9,9,8,7,4,5,1]));
Putting typeof(x) in your second loop reveals that some of your variables are being cast as type string! Still looking into exactly where this is occurring. You can replace
if ( aux[x] == max && (x < final || final == null)) {
with
if ( aux[x] == max && (parseInt(x) < parseInt(final) || final == null)) {
to return the correct value of 9.
Edit:
Very interesting, I was unaware of Javascript's exact handling of arrays in for...in loops. See the following other questions for more information:
JavaScript For-each/For-in loop changing element types
Why is using “for…in” with array iteration such a bad idea?
Also note that you can use arr.forEach(function(element){...}); and the elements are returned with their types intact.
I think the problem is just that the x in aux is not a number so the if statement isn't evaluating correctly. when converted to a number then it returns 9 (below).
(3 == 3 && ("10" < "9" || "9" == null)) evaluates to true
function maxOccurencies(arr) {
var aux = [], max = 0, final = null;
for (var i=0,t=arr.length; i<t; i++) {
aux[arr[i]] = (aux[arr[i]] || 0) + 1;
if (aux[arr[i]] > max) max = aux[arr[i]];
}
for (x in aux) {
if ( aux[x] == max && (parseInt(x) < final || final == null)) {
final = parseInt(x);
}
}
return final;
}
document.write(maxOccurencies([10,10,10,9,9,9,8,7,4,5,1]));
"I'm pulling my hair figuring out why it return 10 instead of 9 in the example."
That's because in this sort of comparison, 10 is smaller than 9,8,7,6,5,4,3, 2 but a bit grater than 1.
:)
This small type correction will fix it:
function maxOccurences(arr) {
aux = [], max = 0, final = null;
for (var i=0,t=arr.length; i<t; i++) {
aux[arr[i]] = (aux[arr[i]] || 0) + 1;
if (aux[arr[i]] > max) max = aux[arr[i]];
}
for (x in aux) {
if ( aux[x] == max && (+x < final || final == null)) {
final = x;
}
}
return final;
}

jQuery if condition 1 or condition 2 is true than

I am trying to alert "yes" if ether of the conditions in my if statement are true:
var a = 2;
var b = 1;
if (a = 1 or b = 1 ) {
alert('yes');// should alert in this case
} else {
alert('no');
}
https://jsfiddle.net/90z7urvd/1/
What do I use for the if, if this is possible?
a = 1 will set the value 1 to variable a. It is not doing a comparison. For comparison, you use === or ==
=== (Identity operator) is the correct way to compare if both the types are same.
if (a === 1 || b === 1 ) {
=== operator won't do the type conversion before the comparison while == does the type conversion before the comparison.
For your or case, You may use || operator
var bootresul = someExpression || anotherExpression
Corrected code
var a = 2;
var b = 1;
if (a === 1 || b === 1 ) {
alert('yes');
} else {
alert('no');
}
You are assiging value rather then comparing
Try like this
if (a == 1 || b == 1)
To compare strictly use ===
Like this
if (a === 1 || b === 1)
JSFIDDLE
you can do this
var a = 2;
var b = 1;
if ((a == 1) || (b == 1 )) {
alert('yes');// should alert in this case
} else {
alert('no');
}
the == is one of the relational operator for checking equality and || is a logical operator that is a notion of logical OR
use this to compare just values
if (a == 1 || b == 1){
}
OR use this to compare values and type of variable
if (a === 1 || b === 1){
}
note : == will just check of values and === this will check value with type of variable
var a = 2;
var b = 1;
if (a == 1 || b == 1 ) {
alert('yes');// should alert in this case
} else {
alert('no');
}
I think you were doing assignment instead of comparison
Try using this:
if(a === 1 || b === 1){
alert('YES!')
}else{
alert('NO!')
}
OR you can use ternary operator condition instead of if else
(a == 1 || b == 1) ? alert('YES!') : alert('NO!')

Javascript condense if statement

I have an if statement in javascript that is
if(prop < 0 || trans < 0 || queue < 0 || proc < 0
|| prop > 1 || trans > 1 || queue > 1 || proc > 1
|| prop == "" || trans == "" || queue == "" || proc == ""){
Is there a way to condense this? For prop, trans, queue, and proc. I want to create an if statement if the values do not fall to be between 0 and 1 or if it has an empty string value
Building off of Jordan's answer:
var checkThese = [prop, trans, queue, proc];
var result = checkTruthinessOf(checkThese);
function checkTruthinessOf(things) {
return things.every(function(el) {
return (el < 0 || el > 1 || el === "");
});
}
See Array.prototype.every()
var checkThese = [prop, trans, queue, proc];
var result = checkTruthinessOf(checkThese);
function checkTruthinessOf(things) {
var returnValue = false;
[].forEach.call(things, function(thing){
if (thing < 0 || thing > 1 || thing == "") returnValue = true;
});
return returnValue;
};
I picked up this practice from jQuery. It eliminates the extra array and just passes in as many arguments as you like. Then use rink's function to validate all it at once.
var result = checkTruthinessOf(prop, trans, queue, proc);
function checkTruthinessOf(/*unlimited arguments*/) {
return Array.prototype.every.call(arguments, function(thing) {
return (thing < 0 || thing > 1 || thing === "");
});
}

Categories

Resources