Realm React native sorted order - sorting

Basically I have a MessageSchema with a date property, on my app I need to query all the messages stored on the database and be able to sort them by their date to display them on a ListView, I do the query as follows:
return realm.objects("Message").sorted('date');
This works, but only one way, the messages are sorted on ascending order only, I haven't found a way to do it on descending order and the docs of the react native only show one example:
let hondas = realm.objects('Car').filtered('make = "Honda"');
// Sort Hondas by mileage
let sortedHondas = hondas.sorted('miles');
Any advice is welcome.
Versions:
react-native: "0.40.0"
realm js: "1.0.2"

return realm.objects("Message").sorted('date', true);
Looking at the source code you can see that the sorted method expects
a descriptor and a Boolean named reverse, that it is set as false unless
you change it, so the code above just reverses the order.

Related

Angular array filter is not working on a list of string

I have an array of string, and want to filter out a particular string after some operation. But, it seems I am doing something wrong there.
this.displayUser.followers.filter(userId=>userId !== this.loggedUser.userid);
Here, followers is an array of string -> string[] and upon some action (say, unfollow); I want to remove the logged user's id from the displayed user's followers list.
However, this filter operation does not seem to work.
On the other hand I tried using splice which is working perfectly fine.
this.displayUser.followers.splice(
this.displayUser.followers.findIndex(userId=>userId === this.loggedUser.userid)
,1);
I am unable to understand what am I doing wrong in the first approach?
Array.filter does not change the array it performs its action on, but returns a new array with values that passed the condition.
In order to use .filter and have the result saved, you can do:
this.displayUser.followers = this.displayUser.followers.filter((userId) => userId !== this.loggedUser.userid);
This will remove all entries where userId === loggedUser.userid.
.splice on the other hand manipulates the array it performs its actions on, hence you will immediately see the results as expected.

Sorting by case using Hibernate

We have a typeahead that allows our customers to do a global search of their clients. Based on a 'filterText', we want to retrieve all the clients where any of the following fields contain the filterText: clientName, clientStreet, clientCity... but now there's a requirement and we want to prioritize the results where the clientName contains the filterText. (They should be shown first)
We currently create a customerSpecification, and the Predicate that it's being used is the following one:
return criteriaBuilder.or(
criteriaBuilder.like(customerName, likeFilter),
criteriaBuilder.like(customerStreet, likeFilter),
criteriaBuilder.like(customerCity, likeFilter),
criteriaBuilder.like(customerState, likeFilter),
criteriaBuilder.like(customerZip, likeFilter),
criteriaBuilder.like(customerCountry, likeFilter),
tempPred
);
and then we use it to get the Page with all the results
customerRepository.findAll(customerSpecification, pageable);
How can we introduce this new requirement? Any approaches?
Some pages suggest to use selectCase, doing something like this:
Expression<Object> caseExpression = criteriaBuilder.selectCase()
.when(criteriaBuilder.like(root.get(CustomerEntity_.name), likeFilter), 1)
.otherwise(2);
Order order = criteriaBuilder.desc(caseExpression);
criteriaQuery.orderBy(order);
But I can't find the way to make it works. I also found some talks about PageRequest, which receives a Sort parameter, but I didn't find how it would help, as this object is too simple for what we're looking for.
Thanks

Clear the sort applied on a table from the code

I am trying to clear the sort applied on a table from the code by using the active and direction fields but with no success:
#ViewChild(MatSort) sort: MatSort;
private clearSort() {
// Reset the sort column
this.sort.active = "";
// Reset the sort direction
this.sort.direction = "";
}
I looked into the Sort Header Documentation but I didn't find any native method that helps to clear an applied sort on a given table.
Any advice would be appreciated.
You can set a default sort option and use sort function on the MatSort api to set that default option.
defaultSort: MatSortable = {
id: 'defColumnName',
start: 'asc',
disableClear: true
};
then use sort function on MatSort directive:
this.sort.sort(this.defaultSort);
//default sort direction
this.sort.direction = 'asc';
Beware that the above code will trigger the sortChange event subscription.
In general, the way to clear a sort is to re-apply the original sort order.
If the original sort order does not have a natural key, you may need to introduce an original order field in your data so you can sort by that field to "clear" any sorting that has occurred since the data loaded.
I haven't used MatSort, but in the absence of someone confirming otherwise, I would assume that to clear the sorting, you need to apply sorting as described above.
If the library supplied a reset, it would have to maintain the data in the original order in memory somewhere, which is why most libraries don't do this.

Sorting a NotesDocumentCollection based on a date field in SSJS

Using Server side javascript, I need to sort a NotesDcumentCollection based on a field in the collection containing a date when the documents was created or any built in field when the documents was created.
It would be nice if the function could take a sort option parameter so I could put in if I want the result back in ascending or descending order.
the reason I need this is because I use database.getModifiedDocuments() which returns an unsorted notesdocumentcollection. I need to return the documents in descending order.
The following code is a modified snippet from openNTF which returns the collection in ascending order.
function sortColByDateItem(dc:NotesDocumentCollection, iName:String) {
try{
var rl:java.util.Vector = new java.util.Vector();
var tm:java.util.TreeMap = new java.util.TreeMap();
var doc:NotesNotesDocument = dc.getFirstDocument();
while (doc != null) {
tm.put(doc.getItemValueDateTimeArray(iName)[0].toJavaDate(), doc);
doc = dc.getNextDocument(doc);
}
var tCol:java.util.Collection = tm.values();
var tIt:java.util.Iterator = tCol.iterator();
while (tIt.hasNext()) {
rl.add(tIt.next());
}
return rl;
}catch(e){
}
}
When you construct the TreeMap, pass a Comparator to the constructor. This allows you to define custom sorting instead of "natural" sorting, which by default sorts ascending. Alternatively, you can call descendingMap against the TreeMap to return a clone in reverse order.
This is a very expensive methodology if you are dealing with large number of documents. I mostly use NotesViewEntrycollection (always sorted according to the source view) or view navigator.
For large databases, you may use a view, sorted according to the modified date and navigate through entries of that view until the most recent date your code has been executed (which you have to save it somewhere).
For smaller operations, Tim's method is great!

Rearranging active record elements in Yii

I am using a CDbCriteria with its own conditions, with & order clauses. However, the order i want to give to the elements in the array is way too complex to specify in the order clause.
The solution i have in mind consists of obtaining the active records with the defined criteria like this
$theModelsINeed = MyModel::model()->findAll($criteria);
and then rearrange the order from my php code. How can i do this? I mean, i know how to iterate through its elements, but i donĀ“t know if it is possible to actually change them.
I have been looking into this link about populating active records, but it seems quite complicated and maybe someone could have some better advice.
Thanks
There is nothing special about Yii's active records. The find family of methods will return an array of objects, and you can sort this array like any other array in PHP.
If you have complex sort criteria, this means that probably the best tool for this is usort. Since you will be dealing with objects, your user-defined comparison functions will look something like this:
function compare($x, $y)
{
// First sort criterion: $obj->Name
if ($x->Name != $y->Name) {
return $x->Name < $y->Name ? -1 : 1; // this is an ascending sort
}
// Second sort criterion: $obj->Age
if ($x->Age != $y->Age) {
return $x->Age < $y->Age ? 1 : -1; // this is a descending sort
}
// Add more criteria here
return 0; // if we get this far, the items are equal
}
If you do want to get an array as a result, you can use this method for fetching data that supports dbCriteria:
$model = MyModel::model()->myScope();
$model->dbCriteria->condition .= " AND date BETWEEN :d1 AND :d2";
$model->dbCriteria->order = 'field1 ASC, field2 DESC';
$model->dbCriteria->params = array(':d1'=>$d1, ':d2'=>$d2);
$theModelsINeed = $model->getCommandBuilder()
->createFindCommand($model->tableSchema, $model->dbCriteria)
->queryAll();
The above example shows using a defined scope and modifying the condition with named parameters.
If you don't need Active Record, you could also look into Query Builder, but the above method has worked pretty well for me when I want to use AR but need an array for my result.

Resources