how to validate if an array is empty using validator - node.js

I need to check if the users have filled in array values or they are empty .
I went through the validator docs
but I don't see any function which works on array .
isEmpty(str) check if the string has a length of zero.

validator validates and sanitizes strings only. so none of the methods in there will help you achieve what you want. just use Array.length property.

If by empty array, you mean: []
This will do:
if(!array.length)
console.log(`I'm not empty`);
If you mean an array with empty values, such as: [null, '']
You can use: .some to check if at least one item is empty, or .every to check that every item is empty.
const array = [null, ''];
!array.some(Boolean); // True if at least one is falsy
!array.every(Boolean); // True if every item is falsy
If you want some custom validation, you can pass your custom function too.
function empty(item) {
// What ever you consider by empty, check it here
// return true if it is empty
if(typeof item === 'string')
return !item.trim();
return !item;
}
array.some(empty); // true if at least one is empty
array.every(empty); // true if all of them are empty

Related

How to remove empty fields on Update

When I remove an array element from a document field, I would like to remove that field, if zero length, or empty object. I do not want fields with empty arrays or empty objects saved on db.
I use this snippet for update document:
await documentInstance.findByIdAndDelete(req.params.id,async(error,doc)=>{
await empInstance.findByIdAndUpdate(employId,{
$pull:{
documents:req.params.id
}
},{omitUndefined:true});
});
When I remove the only item from array, I get an empty array.
Thanks.

How to find the string from string array in firestore

I have a list of documents and each document has a field of a string array named "fav", it has more than 50k emails, there are almost 1000 documents and in each document's "fav" array has variable length including 50k, 20k,10, etc. I was fetching all documents
Firestore.instance.collection("save").snapshots();
through StreamBuilder
StreamBuilder(
stream: Firestore.instance.collection("save").snapshots();,
builder: (context, snapshot) {
if (!snapshot.hasData)
return Text("Loading Data.............");
else {
listdata = snapshot.data.documents;
return _buildBody(snapshot.data.documents);
}
},
)
Now How I can search my required email from each document's field "fav"? I have to perform an operation after finding the required id in the array locally.
The question is not very clear, but for my understanding, this is what you are looking for
Firestore.instance.collection('save')
.where('fav', arrayContains: 'abc#gmail.com').snapshots()
The question is not very clear, but for my understanding, you want to find one e-mail in the array field. This array is contained on each document, and all the documents are "streamed" in a collection of snapshots.
Contains Method: https://api.dartlang.org/stable/2.0.0/dart-core/Iterable/contains.html
bool contains (
Object element
)
Returns true if the collection contains an element equal to element.
This operation will check each element in order for being equal to element, unless it has a more efficient way to find an element equal to element.
The equality used to determine whether element is equal to an element of the iterable defaults to the Object.== of the element.
Some types of iterable may have a different equality used for its elements. For example, a Set may have a custom equality (see Set.identity) that its contains uses. Likewise the Iterable returned by a Map.keys call should use the same equality that the Map uses for keys.
Implementation
bool contains(Object element) {
for (E e in this) {
if (e == element) return true;
}
return false;
}

"new Set" is returning an empty set in nodejs

I was testing some websites using the below function with n, suddenly "new Set" started returning empty Array as the following:
function collectAllSameOriginAnchorsDeep(sameOrigin = true) {
const allElements = [];
// Some coding here
const filtered = allElements
// Some coding here
console.log(filtered) // The items are printed in the log probably
return Array.from(new Set(filtered)); // Nothing is getting returned!
}
If I replace the last line with return Array.from(filtered), then it works fine but I'm using "Set" to remove any repeated values.
Because Set receives iterable object as its input parameter, and will create set object respectively. Hence, we can construct a set from an array — but it will only include distinct elements from that array, aka no duplicate.
And of course, we can also convert a set back to array using Array.from() method.
let set = new Set([1,2,3]); // {1,2,3}
let arr = Array.from(set);//[1,2,3]
So you need to convert set back to array , please check here to understand the difference between set and array.
Hope this will help you!

getSubmittedValue() vs. getValue()

Is that correct:
When I query a value before validation (or if validation failed) I have to use getSubmittedValue();. Once the value is validated, even if I query it in another validation later in the page/control I have to use .getValue(); since getSubmittedValue(); returns null after successful validation?
This xsnippet makes it easier to handle this. It allows you to just call getComponentValue("inputText1") to get either value or submittedValue.
Here's the function for reference:
function getComponentValue(id){
  var field = getComponent(id);
  var value = field.getSubmittedValue();
  if( null == value ){
         // else not yet submitted
         value = field.getValue();
  }
 
  return value
}
There's a slightly easier way: if you're just expecting a simple single-value String, just call:
var compare = firstField.getValueAsString();
Otherwise, call:
var compare = com.ibm.xsp.util.FacesUtil.convertValue(facesContext, firstField);
The former calls the latter anyway, but is obviously a terser syntax. This does what you're looking for and more:
If the value hasn't yet been validated, returns the submitted value
If validation has already passed, returns the value after it's already been processed by any converters and / or content filters, so particularly in cases where you're trying to compare two field values, this should ensure that both values have been properly trimmed, etc., and is therefore less likely to return a false positive than just comparing the raw submitted values.
Found the answer here. So when you want to ensure that 2 text fields have the same value (use case: please repeat your email) and the first box already has a validation that might fail, you need to use submittedValue unless it is null, then you use the value. Code in the validation expression for the second field looks like this:
var firstField = getComponent("inputText1");
var compare = firstField.getSubmittedValue() || firstField.getValue();
compare == value;
You have to love it.

Efficient way to search object from list of object in c#

I have a list which contains more than 75 thousand object. To search item from list currently I am using following code.
from nd in this.m_ListNodes
where
nd.Label == SearchValue.ToString()
select
nd;
Is this code is efficient?
How often do you need to search the same list? If you're only searching once, you might as well do a straight linear search - although you can make your current code slightly more efficient by calling SearchValue.ToString() once before the query.
If you're going to perform this search on the same list multiple times, you should either build a Lookup or a Dictionary:
var lookup = m_ListNodes.ToLookup(nd => nd.Label);
or
var dictionary = m_ListNodes.ToDictionary(nd => nd.Label);
Use a dictionary if there's exactly one entry per label; use a lookup if there may be multiple matches.
To use these, for a lookup:
var results = lookup[SearchValue.ToString()];
// results will now contain all the matching results
or for a dictionary:
WhateverType result;
if (dictionary.TryGetValue(SearchValue.ToString(), out result))
{
// Result found, stored in the result variable
}
else
{
// No such item
}
No. It would be better if you used a Dictionary or a HashSet with the label as the key. In your case a Dictionary is the better choice:
var dictionary = new Dictionary<string, IList<Item>>();
// somehow fill dictionary
IList<Item> result;
if(!dictionary.TryGetValue(SearchValue.ToString(), out result)
{
// if you need an empty list
// instead of null, if the SearchValue isn't in the dictionary
result = new List<Item>();
}
// result contains all items that have the key SearchValue

Resources