Issue with LokiJS: The DynamicView().branchResultSet method does not apply sorting to the collection

I'm encountering an issue retrieving data from a branchResultSet after applying the applySort function on the view. I'm utilizing this method to restrict the result set to 10 records for better performance, rather than fetching the entire dataset. Interestingly, when I solely use the data method, it functions as intended.

Here is an example of the code:

switch() {
  // ...
  case 'Name':
  // Code added elsewhere; provided as an illustration of initializing the variable studentView.
  this.studentView = studentColl.addDynamicView('view');
  /////////////////////////////////////////////////////

  this.studentsView.applySort((a: IStudent, b: IStudent) => {
    if (a.firstName.toLowerCase() < b.firstName.toLowerCase()) {
      return -1;
    }
    if (a.firstName.toLowerCase() > b.firstName.toLowerCase()) {
      return 1;
    }
    return 0;
  }).applySort((a, b) => {
    if (a.lastName.toLowerCase() < b.lastName.toLowerCase()) {
      return -1;
    }
    if (a.lastName.toLowerCase() > b.lastName.toLowerCase()) {
      return 1;
    }
    return 0;
  });
  break;
};

this.students = this.studentsView.branchResultset(lokiViews.viewPaging, { pageStart: 0, pageSize: 10 }).data();
//...

My expectation was to observe the collection sorted accordingly.

Upon using this.studentView.data(), the data appears sorted as expected.

The utilization of applyWhere yields the anticipated outcome.

However, employing the branchResultSet function did not yield the desired results with applySimpleSort(param).

applyFind also performs as intended.

The stumbling blocks are specifically related to both Sort methods.

I am working with StencilJS and TypeScript, although I do not attribute the issue to these frameworks since a similar code snippet running on Vanilla HTML-JavaScript presented the same challenge.

Answer №1

The code snippet provided for Resultset.prototype.copy does not include a sort operation before branching, but it can be easily added. Just implement the sorting before calling the branch method.

if (this.studentsView.sortDirty || this.studentsView.resultsdirty) {
    this.studentsView.performSortPhase({
        suppressRebuildEvent: true
    });
}
this.students = this.studentsView.branchResultset(lokiViews.viewPaging, { pageStart: 0, pageSize: 10 }).data();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for effectively utilizing Formik's handleChange method multiple times to update a single value

Utilizing Material-UI along with Formik, I am trying to enable two input fields to modify a single value. The scenario involves having a TextField and a Slider where both inputs should have the ability to change the value for period. When assigning the sam ...

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

The .ts source file is mysteriously missing from the development tool's view after being deployed

When I work locally, I can see the .ts source files, but once I deploy them, they are not visible in any environment. Despite setting my sourcemap to true and configuring browserTargets for serve, it still doesn't work. Can someone help with this issu ...

Storing the output of a GET request in a text file can lead to a never-ending loop

After attempting to save a String obtained from a GET request into a text file, I encountered an unexpected infinite loop issue. It seems that without utilizing created(), the process fails entirely, resulting in story remaining empty. <div id="app"> ...

The parameter 'Value | ValueXY' cannot be assigned to the type 'AnimatedValue<0>'

Recently, I delved into React Native documentation on Animations which can be found here: https://reactnative.dev/docs/animated After reading the docs, I decided to try out some code snippets: import {Animated as RNAnimated} from 'react-native' ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

AJAX Triggering fopen Function

In the process of developing a WebApp, I have a requirement to use AJAX to send both text content and a filename to a PHP script located in the same directory as the JavaScript source code. The ultimate goal is to have the PHP script save the file on the ...

Stopping an HTML5 range input at a specific number: Tips and tricks

Does anyone have suggestions on how to use angularjs to stop a range slider at 75? I attempted it but it doesn't seem like the best approach. Any guidance would be appreciated. [EDIT for clarification after max=75 answer] Just to clarify, I want to di ...

Automatically update certain attributes of an object with Spring MVC's auto-refresh feature

Currently, I have a table in JSP where I am populating all object attributes using Spring MVC. The backend is providing a list of DTO's which are then being added to the ModelView. In the JSP, we iterate through this DTO list and display it in the tab ...

Script to automatically open a PDF document immediately after it has been generated

Can Apps Script in Google Sheets automatically open a PDF file right after it's created? I have a script that generates a PDF from a Google Sheet and saves it on Google Drive. Is there a way for the script to also open the PDF so it can be easily pri ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

How to choose an item from a dropdown list using its item number with jQuery

Is there a way to select an item in a dropdown menu by its item number using jQuery? <select id="selectbox" style="width: 220px;"> <option value="Option 1">Option 1</option> <option value="Option 2">Option 2</option> < ...

Using jQuery to Extract HTML Content from a JSON Object

I'm completely lost on what I'm doing incorrectly, but the JSON string I have looks like this: jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World< ...

Interactive Animation with Three.js Curved Path

I am attempting to animate a 2D curve in Three.js gradually. Because I will require more than 4 control points, I have decided against using Bezier curves and instead opted for a SplineCurve. When I check the position of geometry.vertices of my line, I no ...

Improved method for flattening arrays

Attempting to extract objects from an array to a new array. Searching for a more efficient method. Approach used: Created a new array with filter1, flattened it, then created another array with filter3. filter1 = myArray.map((a => a.courseEnrolled); f ...

When placed in a conditional, the type of the body variable changes from a string to undefined

Unexpectedly, the final if block fails to retain the value of the body variable and transforms it into undefined. While the console log statement just before the block correctly displays the type of the variable as a "string", during the condition check an ...

What is the process for executing a Js file on a website?

I am looking to automate some tasks on a website that I do not own. Specifically, I need to automatically fill out a form and perform certain clicking actions. Can JavaScript be used for this purpose? I am unsure how to run a .js file on a site without the ...

Ways to darken a theme when displaying a pop-up

I recently added a pop-up feature to my portfolio website and utilized Bootstrap classes to enhance its functionality. In order to make the pop-up object more prominent, I wanted to darken the background when opening the pop-up. However, some elements in t ...

What is the best way to incorporate Electron browser windows within Angular-CLI components?

How can I use electron browser window inside components in angular-cli if it doesn't accept it? I encountered an error with fs.existsync. Are there any alternative options to integrate electron with angular2 components? var electron = require(&apos ...