How to check if less than 2 of 3 variables are empty - javascript

I need to check that there are at least 2 values before running a script, but can't seem to get the condition to fire.
When I use if (risForm) {... the script runs when risForm is filled, and when I use if (!(risForm)) {... the script runs if risForm is empty, but I can't seem to work out how to check if any 2 of the three is full... I've tried this:
if ((!(risForm)) + (!(runForm)) + (!(angForm)) < 2) {...
along with a numerous adjustments to precise formatting/bracketting, but it's not getting me anywhere!

Make an array of the variables, filter by Boolean, then check the length of the array:
const forms = [risForm, runForm, angForm];
if (forms.filter(Boolean).length < 2) {
throw new Error('Not enough forms are filled');
}
// rest of the code
You can avoid creating an intermediate array by using reduce instead, if you wanted:
const filledFormCount = forms.reduce((a, form) => a + Boolean(form), 0);
if (filledFormCount < 2) {
throw new Error('Not enough forms are filled');
}

If you can have all your variables inside an array, you can do
yourArray.filter(Boolean).length >= 2
To break it apart, let's rewrite the above in a more verbose fashion:
yourArray
.filter(
function (variable) {
return Boolean(variable)
}
)
.length >= 2
Now, array.filter() gets every variable in the array and runs each as the argument for the function inside the parens, in this case: Boolean(). If the return value is truthy, the variable is "filtered in", if not it is "filtered out". It then returns a new array without the variables that were filtered out.
Boolean() is a function that will coerce your value into either true or false. If there's a value in the variable, it will return true... But there's a catch: it will return false for zeroes and empty strings - beware of that.
Finally, we use .length to count how many variables were "filtered in" and, if it's more than two, you can proceed with the code.
Maybe this pseudo code can illustrate it better:
const variables = ['foo', undefined, 'bar'];
variables.filter(Boolean).length >= 2;
['foo', undefined, 'bar'].filter(Boolean).length >= 2;
keepIfTruthy(['foo' is truthy, undefined is falsy, 'bar' is truthy]).length >= 2;
['foo', 'bar'].length >= 2;
2 >= 2;
true;

Javascript's true and false are useful here because when coerced to a number, they become respectively 1 and 0. So...
function foo(a,b,c) {
const has2of3 = !!a + !!b + !!c;
if ( has2of3 ) {
// Do something useful here
}
}
One caveat, though is that the empty string '' and 0 are falsy, which means they would be treated as not present. If that is an issue, you could do something like this:
function foo(a,b,c) {
const hasValue = x => x !== undefined && x !== null;
const has2of3 = hasValue(a) + hasValue(b) + hasValue(c);
if ( has2of3 ) {
// Do something useful here
}
}

let risForm = "a",
runForm = "",
angForm = "";
let arr = [risForm, runForm, angForm]
let res = arr.filter(el => !el || el.trim() === "").length <= 1
console.log(res)

There many ways to solve this. Lets try with basic idea. You want to make a reusable code and something that support multiple variables, also condition value might change. This means, we need to define an array of the form values and a condition value to verify. Then we can apply a function to verify the condition. So let's try some code:
let risForm, runForm, angForm;
risForm = 'Active';
// runForm = 3;
const formValues = [risForm, runForm, angForm];
const minFilledForms = 2;
const hasValue = a => !!a && a !== undefined && a !== null;
verifyForms();
function verifyForms() {
let filledForms = formValues.reduce((count, form) => count + hasValue(form), 0);
if (filledForms < minFilledForms) {
console.log(`Only ${filledForms} of ${formValues.length} forms have filled. Minimum ${minFilledForms} forms are requiered.`);
}
console.log('Continue...');
}

Related

why cant I access the object values within state when they are clearly shown? [duplicate]

In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:
// where this array is hundreds of entries long, with a mix
// of the two examples given
var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
This is giving me problems because I need to iterate through the array at times, and the inconsistency is throwing me errors like so:
for (i=0; i<test.length; i++) {
// ok on i==0, but 'cannot read property of undefined' on i==1
console.log(a.b.c);
}
I am aware that I can say if(a.b){ console.log(a.b.c)}, but this is extraordinarily tedious in cases where there are up to 5 or 6 objects nested within one another. Is there any other (easier) way that I can have it ONLY do the console.log if it exists, but without throwing an error?
Update:
If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
TypeScript has added support for optional chaining in version 3.7.
// use it like this
obj?.a?.lot?.of?.properties
Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:
A quick workaround is using a try/catch helper function with ES6 arrow function:
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));
// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));
What you are doing raises an exception (and rightfully so).
You can always do:
try{
window.a.b.c
}catch(e){
console.log("YO",e)
}
But I wouldn't, instead think of your use case.
Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?
Usually, you'd like to actually validate what sort of object you're dealing with.
Also, on a side note you should not use statements like if(a.b) because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined
If I am understanding your question correctly, you want the safest way to determine if an object contains a property.
The easiest way is to use the in operator.
window.a = "aString";
//window should have 'a' property
//lets test if it exists
if ("a" in window){
//true
}
if ("b" in window){
//false
}
Of course you can nest this as deep as you want
if ("a" in window.b.c) { }
Not sure if this helps.
Try this. If a.b is undefined, it will leave the if statement without any exception.
if (a.b && a.b.c) {
console.log(a.b.c);
}
If you are using lodash, you could use their has function. It is similar to the native "in", but allows paths.
var testObject = {a: {b: {c: 'walrus'}}};
if(_.has(testObject, 'a.b.c')) {
//Safely access your walrus here
}
If you use Babel, you can already use the optional chaining syntax with #babel/plugin-proposal-optional-chaining Babel plugin. This would allow you to replace this:
console.log(a && a.b && a.b.c);
with this:
console.log(a?.b?.c);
If you have lodash you can use its .get method
_.get(a, 'b.c.d.e')
or give it a default value
_.get(a, 'b.c.d.e', default)
I use undefsafe religiously. It tests each level down into your object until it either gets the value you asked for, or it returns "undefined". But never errors.
This is a common issue when working with deep or complex json object, so I try to avoid try/catch or embedding multiple checks which would make the code unreadable, I usually use this little piece of code in all my procect to do the job.
/* ex: getProperty(myObj,'aze.xyz',0) // return myObj.aze.xyz safely
* accepts array for property names:
* getProperty(myObj,['aze','xyz'],{value: null})
*/
function getProperty(obj, props, defaultValue) {
var res, isvoid = function(x){return typeof x === "undefined" || x === null;}
if(!isvoid(obj)){
if(isvoid(props)) props = [];
if(typeof props === "string") props = props.trim().split(".");
if(props.constructor === Array){
res = props.length>1 ? getProperty(obj[props.shift()],props,defaultValue) : obj[props[0]];
}
}
return typeof res === "undefined" ? defaultValue: res;
}
I like Cao Shouguang's answer, but I am not fond of passing a function as parameter into the getSafe function each time I do the call. I have modified the getSafe function to accept simple parameters and pure ES5.
/**
* Safely get object properties.
* #param {*} prop The property of the object to retrieve
* #param {*} defaultVal The value returned if the property value does not exist
* #returns If property of object exists it is returned,
* else the default value is returned.
* #example
* var myObj = {a : {b : 'c'} };
* var value;
*
* value = getSafe(myObj.a.b,'No Value'); //returns c
* value = getSafe(myObj.a.x,'No Value'); //returns 'No Value'
*
* if (getSafe(myObj.a.x, false)){
* console.log('Found')
* } else {
* console.log('Not Found')
* }; //logs 'Not Found'
*
* if(value = getSafe(myObj.a.b, false)){
* console.log('New Value is', value); //logs 'New Value is c'
* }
*/
function getSafe(prop, defaultVal) {
return function(fn, defaultVal) {
try {
if (fn() === undefined) {
return defaultVal;
} else {
return fn();
}
} catch (e) {
return defaultVal;
}
}(function() {return prop}, defaultVal);
}
Lodash has a get method which allows for a default as an optional third parameter, as show below:
const myObject = {
has: 'some',
missing: {
vars: true
}
}
const path = 'missing.const.value';
const myValue = _.get(myObject, path, 'default');
console.log(myValue) // prints out default, which is specified above
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Imagine that we want to apply a series of functions to x if and only if x is non-null:
if (x !== null) x = a(x);
if (x !== null) x = b(x);
if (x !== null) x = c(x);
Now let's say that we need to do the same to y:
if (y !== null) y = a(y);
if (y !== null) y = b(y);
if (y !== null) y = c(y);
And the same to z:
if (z !== null) z = a(z);
if (z !== null) z = b(z);
if (z !== null) z = c(z);
As you can see without a proper abstraction, we'll end up duplicating code over and over again. Such an abstraction already exists: the Maybe monad.
The Maybe monad holds both a value and a computational context:
The monad keeps the value safe and applies functions to it.
The computational context is a null check before applying a function.
A naive implementation would look like this:
⚠️ This implementation is for illustration purpose only! This is not how it should be done and is wrong at many levels. However this should give you a better idea of what I am talking about.
As you can see nothing can break:
We apply a series of functions to our value
If at any point, the value becomes null (or undefined) we just don't apply any function anymore.
const abc = obj =>
Maybe
.of(obj)
.map(o => o.a)
.map(o => o.b)
.map(o => o.c)
.value;
const values = [
{},
{a: {}},
{a: {b: {}}},
{a: {b: {c: 42}}}
];
console.log(
values.map(abc)
);
<script>
function Maybe(x) {
this.value = x; //-> container for our value
}
Maybe.of = x => new Maybe(x);
Maybe.prototype.map = function (fn) {
if (this.value == null) { //-> computational context
return this;
}
return Maybe.of(fn(this.value));
};
</script>
Appendix 1
I cannot explain what monads are as this is not the purpose of this post and there are people out there better at this than I am. However as Eric Elliot said in hist blog post JavaScript Monads Made Simple:
Regardless of your skill level or understanding of category theory, using monads makes your code easier to work with. Failing to take advantage of monads may make your code harder to work with (e.g., callback hell, nested conditional branches, more verbosity).
Appendix 2
Here's how I'd solve your issue using the Maybe monad from monetjs
const prop = key => obj => Maybe.fromNull(obj[key]);
const abc = obj =>
Maybe
.fromNull(obj)
.flatMap(prop('a'))
.flatMap(prop('b'))
.flatMap(prop('c'))
.orSome('🌯')
const values = [
{},
{a: {}},
{a: {b: {}}},
{a: {b: {c: 42}}}
];
console.log(
values.map(abc)
);
<script src="https://www.unpkg.com/monet#0.9.0/dist/monet.js"></script>
<script>const {Maybe} = Monet;</script>
In str's answer, value 'undefined' will be returned instead of the set default value if the property is undefined. This sometimes can cause bugs. The following will make sure the defaultVal will always be returned when either the property or the object is undefined.
const temp = {};
console.log(getSafe(()=>temp.prop, '0'));
function getSafe(fn, defaultVal) {
try {
if (fn() === undefined || fn() === null) {
return defaultVal
} else {
return fn();
}
} catch (e) {
return defaultVal;
}
}
You can use optional chaining from the ECMAScript standart.
Like this:
a?.b?.c?.d?.func?.()
I answered this before and happened to be doing a similar check today. A simplification to check if a nested dotted property exists. You could modify this to return the value, or some default to accomplish your goal.
function containsProperty(instance, propertyName) {
// make an array of properties to walk through because propertyName can be nested
// ex "test.test2.test.test"
let walkArr = propertyName.indexOf('.') > 0 ? propertyName.split('.') : [propertyName];
// walk the tree - if any property does not exist then return false
for (let treeDepth = 0, maxDepth = walkArr.length; treeDepth < maxDepth; treeDepth++) {
// property does not exist
if (!Object.prototype.hasOwnProperty.call(instance, walkArr[treeDepth])) {
return false;
}
// does it exist - reassign the leaf
instance = instance[walkArr[treeDepth]];
}
// default
return true;
}
In your question you could do something like:
let test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
containsProperty(test[0], 'a.b.c');
I usually use like this:
var x = object.any ? object.any.a : 'def';
You can avoid getting an error by giving a default value before getting the property
var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
for (i=0; i<test.length; i++) {
const obj = test[i]
// No error, just undefined, which is ok
console.log(((obj.a || {}).b || {}).c);
}
This works great with arrays too:
const entries = [{id: 1, name: 'Scarllet'}]
// Giving a default name when is empty
const name = (entries.find(v => v.id === 100) || []).name || 'no-name'
console.log(name)
Unrelated to the question's actual question, but might be useful for people coming to this question looking for answers.
Check your function parameters.
If you have a function like const x({ a }) => { }, and you call it without arguments x(); append = {} to the parameter: const x({ a } = {}) => { }.
What I had
I had a function like this:
const x = ({ a }) => console.log(a);
// This one works as expected
x({ a: 1 });
// This one errors out
x();
Which results in "Uncaught TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined."
What I switched it to (now works).
const x = ({ a } = {}) => console.log(a);
// This one works as expected
x({ a: 1 });
// This now works too!
x();

Filter an array of objects using the filter method with multiple tests

I'd like to filter an array of objects based on multiple tests. For this example, I want to filter an array of objects if the values for the keys aren't null, and that one value for one key is less than 90. I'm currently doing this with a for loop like so:
let filtered = []
for (let i = 0; i < articles.length; i++) {
if (articles[i].title !== null && articles[i].title.length <= 90 &&
articles[i].date !== null &&
articles[i].image !== null &&
articles[i].description !== null &&
articles[i].link !== null) {
filtered.push(articles[i])
}
}
But it's pretty clumpy and I know the filter method can achieve something similar. But I'm unsure if it can check multiple keys and their values with the same test whilst checking if a specific value passes an independent test too.
Try:
articles.filter(article =>
Object.values(article).every(x => (x !== null))
&& article.title.length <= 90
)
Let's break this down:
articles.filter(article => ...)
.filter is a function property of type that accepts a callback argument, which it calls for each item. Essentially, we're passing it a function - not executing it right away, which it can call at its leisure. It's sort of like:
let a = alert;
We're not calling the alert function, we're just saving it to a variable. In the case of .filter, we're using it as a pseudo-variable - an argument. Internally, all .filter is doing is:
Array.prototype.filter(callbackFunc) {
newArr = [];
for (i=0;i<this.length;i++){
if (callbackFunc(this[i]) === false){ // We're calling `callbackFunc` manually, for each item in the loop.
newArr.push(this[i]);
}
}
return newArr;
}
The next bit to explain is the actual callback function we're using. It's defined with ES6 arrow syntax, but it's the equivalent of:
articles.filter(function(article){
return Object.values(article).every(x => (x !== null))
&& article.title.length <= 90
})
The first line of the callback function, Object.values(article).every(x => (x !== null)), can be broken down to:
let values = Object.values(article); // Get the value of all of the keys in the object
function checkFunction(item){ // Define a helper function
return (x !== null); // Which returns if an item is _not_ null.
}
let result = values.every(checkFunction); // Run `checkFunction` on every item in the array (see below), and ensure it matches _all_ of them.
Finally, we just need to clarify what every does. It's another example of functional JS, where functions accept callback functions as parameters. The internal code looks like this:
Array.prototype.every(callbackFunc) {
for (i=0;i<this.length;i++){
if (callbackFunc(this[i]) === false){ // We're calling `callbackFunc` manually, for each item in the loop.
return false;
}
}
// In JS, returning a value automatically stops execution of the function.
// So this line of code is only reached if `return false` is never met.
return true;
}
And && article.title.length <= 90 should hopefully be self-explanatory: while .every returns a boolean value (true or false), a true will only be returned by the callback function to the filter if the second condition is also met, i.e if the every returns true and article.title.length <= 90
The filter method does exactly this: it takes a conditional (just like that in your if statement and adds it to the array if the condition is met. Your code almost matches the filter syntax exactly, actually:
let filtered = articles.filter(article =>
article.title !== null
article.title.length <= 90 &&
article.date !== null &&
article.image !== null &&
article.description !== null &&
article.link !== null);
yes filter can do this, it just takes a function and applies it to each item in the array
array.filter(x => x.title != null && ... etc)
the examples in this section is pretty much what you are doing https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Filtering_invalid_entries_from_JSON

Simple way to return default value If accessing properties of possibly undefined values

If accessing properties of undefined value, I'm getting an exception:
let object = {}
let n = object["foo"].length;
VM186:1 Uncaught TypeError: Cannot read property 'length' of undefined
at :1:12
I want to get a default value in this case instead of an exception, but the way I'm doing it now seems too verbose:
let n = 0;
if (object.hasOwnProperty("foo")) {
n = object["foo"].length;
}
Is there a more simple and elegant way to do this? Possibly, using ES6.
The method mentioned by #lleaon will work only when the value is undefined and won't work for other falsy values like null.
Here is a technique I use often to safely access nested objects in JavaScript. I picked it up a year ago from another SO answer.
const obj = {};
const arrLength = (obj.foo || []) || 0;
console.log(arrLength); // 0
You can check deep nest level like this,
const obj = {};
const arrLength = ((obj.nestedObj || {}).foo || []) || 0;
console.log(arrLength); // 0
In case you're iterested, I wrote a blog post on it a while back.
Safely Accessing Nested Objects in JavaScript
Not sure if more elegant, but object destructuring can assign default values.
It wont prevent you from null values though. Just undefined
const obj = {};
const { foo: { length = 0 } = [] } = obj;
console.log(length)
using es6 you can check whether any key is there for the object by checking using Object.keys(object) which will give an array of keys Object.keys, checking it with the length will give that object is empty or not and also checking one more condition whether the constructor of object is an Object.
Please see the below code. if those two conditions are satisfied which means object is empty and you can assign a default value
let object = {}
if(Object.keys(object).length === 0 && object.constructor === Object){
// assign a default value if the object is empty
object["foo"] = "bar"
}
console.log("object is empty default value will be assigned", object)
Try ternary operator:
let n =object["foo"] ? object["foo"].length : 0;
To not write twice object["foo"] you can also do something like that:
let n = object["foo"];
n = n ? n.length : 0;
We have two possible undefined values to check. First, the key needs to exist on dictionary. After that, the object should be an array or a struct with the property length.
One great way to go is to use || to define a default value when undefined. But it will not work if you tried to check length of an undefined value, without dealing with this first.
Example
let object = {};
let r = (object["foo"] || 333);
let l = r.length || 111;
let oneLiner = (object["foo"] || 333).length || 111;
console.log("Default Value: " + r);
console.log("Default Length: " + l);
console.log("OneLiner: " + oneLiner);
Another Example
A simpler example, closer of your use case;
let object = {};
let length = (object["foo"] || []).length;
console.log(length);

Returning null or nothing instead of empty array with array.filter

Is there a vanilla js way of returning null (or nothing) instead of an empty array[]
from Array.prototype.filter when no elements are found?
Some context:
let arr = [1,2,3,1,1]
let itemsFound = arr.filter(e=> e===6)
if(itemsFound){ // always true, []===true
// do something
}
The if will always evaluate to true as filter returns an empty array[].
And an empty array is 'true' in javascript. Of course I can do,
if(itemsFound.length > 0){
// do something
}
But I think just, if(itemsFound){} is neater.
The answer would not require additional js libraries.
Additional context
Coming from an OO background, I found it quite funky that objects and functions
could be treated like Boolean. But felt it was intuitive after getting used to it.
There are times that I would forget that Array.filter returns an empty array [] when no elements are found. And [] === true. This causes unnecessary bugs.
As with the answers and feedback received of now, I don't think this question can be answered except with a new implementation of Array.filter.
With that said, the accepted answer is the closest to what I have in mind.
you can do something like this, if you just want to check if it exists or not
let arr = [1,2,3,1,1]
let itemsFound = arr.filter(e=> e===6).length
console.log(itemsFound);
if(itemsFound){ // always true
// do something
}
or something like this
let arr = [1,2,3,1,1]
let itemsFound = arr.filter(e=> e===6)
itemsFound = (itemsFound.length > 0 ? itemsFound : false);
console.log(itemsFound)
if(itemsFound){ // always true
// do something
}
Or something like this
Array.prototype.isEmpty = function(){
return this.length == 0;
}
let arr = [1,2,3,1,1];
arr.isEmpty();
let itemsFound = arr.filter(e=> e===6)
if(itemsFound.isEmpty()){ // always true
// do something
console.log('OK');
}
You could use the length property of an array and take the value as truthy/falsy value for the condition.
function getValues(array) {
const result = array.filter(e => e === 6);
return result.length ? result : null;
}
console.log(getValues([1, 2, 3, 1, 1]));

How can I check JavaScript arrays for empty strings?

I need to check if array contains at least one empty elements. If any of the one element is empty then it will return false.
Example:
var my_arr = new Array();
my_arr[0] = "";
my_arr[1] = " hi ";
my_arr[2] = "";
The 0th and 2nd array elements are "empty".
You can check by looping through the array with a simple for, like this:
function NoneEmpty(arr) {
for(var i=0; i<arr.length; i++) {
if(arr[i] === "") return false;
}
return true;
}
You can give it a try here, the reason we're not using .indexOf() here is lack of support in IE, otherwise it'd be even simpler like this:
function NoneEmpty(arr) {
return arr.indexOf("") === -1;
}
But alas, IE doesn't support this function on arrays, at least not yet.
You have to check in through loop.
function checkArray(my_arr){
for(var i=0;i<my_arr.length;i++){
if(my_arr[i] === "")
return false;
}
return true;
}
You can try jQuery.inArray() function:
return jQuery.inArray("", my_arr)
Using a "higher order function" like filter instead of looping can sometimes make for faster, safer, and more readable code. Here, you could filter the array to remove items that are not the empty string, then check the length of the resultant array.
Basic JavaScript
var my_arr = ["", "hi", ""]
// only keep items that are the empty string
new_arr = my_arr.filter(function(item) {
return item === ""
})
// if filtered array is not empty, there are empty strings
console.log(new_arr);
console.log(new_arr.length === 0);
Modern Javascript: One-liner
var my_arr = ["", "hi", ""]
var result = my_arr.filter(item => item === "").length === 0
console.log(result);
A note about performance
Looping is likely faster in this case, since you can stop looping as soon as you find an empty string. I might still choose to use filter for code succinctness and readability, but either strategy is defensible.
If you needed to loop over all the elements in the array, however-- perhaps to check if every item is the empty string-- filter would likely be much faster than a for loop!
Nowadays we can use Array.includes
my_arr.includes("")
Returns a Boolean
You could do a simple help method for this:
function hasEmptyValues(ary) {
var l = ary.length,
i = 0;
for (i = 0; i < l; i += 1) {
if (!ary[i]) {
return false;
}
}
return true;
}
//check for empty
var isEmpty = hasEmptyValues(myArray);
EDIT: This checks for false, undefined, NaN, null, "" and 0.
EDIT2: Misread the true/false expectation.
..fredrik
function containsEmpty(a) {
return [].concat(a).sort().reverse().pop() === "";
}
alert(containsEmpty(['1','','qwerty','100'])); // true
alert(containsEmpty(['1','2','qwerty','100'])); // false
my_arr.includes("")
This returned undefined instead of a boolean value so here's an alternative.
function checkEmptyString(item){
if (item.trim().length > 0) return false;
else return true;
};
function checkIfArrayContainsEmptyString(array) {
const containsEmptyString = array.some(checkEmptyString);
return containsEmptyString;
};
console.log(checkIfArrayContainsEmptyString(["","hey","","this","is","my","solution"]))
// *returns true*
console.log(checkIfArrayContainsEmptyString(["yay","it","works"]))
// *returns false*
yourArray.join('').length > 0
Join your array without any space in between and check for its length. If the length, turns out to be greater than zero that means array was not empty. If length is less than or equal to zero, then array was empty.
I see in your comments beneath the question that the code example you give is PHP, so I was wondering if you were actually going for the PHP one? In PHP it would be:
function hasEmpty($array)
{
foreach($array as $bit)
{
if(empty($bit)) return true;
}
return false;
}
Otherwise if you actually did need JavaScript, I refer to Nick Craver's answer
Just do a len(my_arr[i]) == 0; inside a loop to check if string is empty or not.
var containsEmpty = !my_arr.some(function(e){return (!e || 0 === e.length);});
This checks for 0, false, undefined, "" and NaN.
It's also a one liner and works for IE 9 and greater.
One line solution to check if string have empty element
let emptyStrings = strArray.filter(str => str.trim().length <= 0);
let strArray = ['str1', '', 'str2', ' ', 'str3', ' ']
let emptyStrings = strArray.filter(str => str.trim().length <= 0);
console.log(emptyStrings)
One line solution to get non-empty strings from an array
let nonEmptyStrings = strArray.filter(str => str.trim().length > 0);
let strArray = ['str1', '', 'str2', ' ', 'str3', ' ']
let nonEmptyStrings = strArray.filter(str => str.trim().length > 0);
console.log(nonEmptyStrings)
If you only care about empty strings then this will do it:
const arr = ["hi","hello","","jj"]
('' in arr) //returns false
the last line checks if an empty string was found in the array.
I don't know if this is the most performant way, but here's a one liner in ES2015+:
// true if not empty strings
// false if there are empty strings
my_arr.filter(x => x).length === my_arr.length
The .filter(x => x) will return all the elements of the array that are not empty nor undefined. You then compare the length of the original array. If they are different, that means that the array contains empty strings.
You have to check in through the array of some functions.
if isEmptyValue is true that means the array has an empty string otherwise not.
const arr=['A','B','','D'];
const isEmptyValue = arr.some(item => item.trim() === '');
console.log(isEmptyValue)
array.includes("") works just fine.
Let a = ["content1", "" , "content2"];
console.log(a.includes(""));
//Output in console
true

Categories

Resources