Why is the table not sorting when I apply filters?

I am encountering an issue where the data filters and table sorting are not working together. When I apply filters, the sorting functionality stops working. The filters work fine independently, but once applied, they interfere with the sorting feature. Any help would be appreciated.

table-filter.pipe.ts

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "tableFilter"
})

export class TableFilterPipe implements PipeTransform {
  transform(list: any[], filters: any) {
    const keys = Object.keys(filters).filter(key => filters[key]);
    const filterUser = (user: { [x: string]: any; }) =>
      keys.every(key => {
        if (key == "sdob") {
          return new Date(user["dob"]) >= new Date(filters[key]);
        } else if (key == "edob") {
          return new Date(filters[key]) >= new Date(user["dob"]);
        } else {
          return user[key] === filters[key];
        }
      });
    return keys.length ? list.filter(filterUser) : list;
  }
}

app.component.ts

sort(property: any) {
    this.isDesc = !this.isDesc;
    this.column = property;
    let direction = this.isDesc ? 1 : -1;
    this.allUser.sort(function (a: { [x: string]: number; }, b: { [x: string]: number; }) {
      if (a[property] < b[property]) {
        return -1 * direction;        
      }
      else if (a[property] > b[property]) {
        return 1 * direction;
      }
      else {
        return 0;
      }
    });
  };

Live:

Answer №1

There seems to be a synchronization issue between your TypeScript code and the generated DOM.

To resolve this, make sure to pass the filtered users (filteredUsers) in your sort function. Currently, the sorting is being applied to the entire list of users (business logic part) even after filtering them out in the DOM (DOM part). This behavior is not intended:

(click)="sort('first_name', filteredUsers)">First Name</th>
(click)="sort('last_name', filteredUsers)">Last Name</th>

In the TypeScript part, update the sort method as follows:

  sort(property: any, filteredUsers) {
    this.isDesc = !this.isDesc;
    this.column = property;
    let direction = this.isDesc ? 1 : -1;
    filteredUsers.sort(function(
      a: { [x: string]: number },
      b: { [x: string]: number }
    ) {
      if (a[property] < b[property]) {
        return -1 * direction;
      } else if (a[property] > b[property]) {
        return 1 * direction;
      } else {
        return 0;
      }
    });
  }

Check out the DEMO for reference.

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

Click on the input field to give it focus before adding a class during the page

Alright, so here's the deal - I have an input field with the class .cf-se-input. I want this field to be focused using jQuery as soon as the document is ready. Additionally, if the field is focused either by the user clicking on it or through jQuery f ...

What is the best way to dynamically add a stylesheet using JavaScript/jQuery?

I've been scouring the web for a solution to a particular issue, but so far I'm coming up empty-handed. We're working with Umbraco CMS for a client's website, and it seems we can't insert conditional comments in the <head> se ...

simulate express-jwt middleware functions for secure routes

I am currently facing an issue with my code snippet, which looks like this: import app from '../src/app'; beforeAll(() => jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => { ...

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

Create the final APK file using Phonegap build directly from your local machine, without the need to

While I've been using Phonegap CLI to develop my android apps and everything has been working well, I encountered an issue when trying to create the final .apk file. I have all the necessary tools - SDK, JDK, Java, and environment variables configure ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } expor ...

When using Node.js with Firebase, information is not stored in the session

I've been attempting to implement session management in my application to keep track of user log-ins and other activities. However... Whenever I try the simplest way, I consistently encounter this error: Warning: connect.session() MemoryStore is ...

Closing the Bootstrap navbar collapse by clicking anywhere outside of the menu area

Excuse my lack of experience, but I have a question. I am trying to make Bootstrap "navbar-collapse" close when clicking away or on one of the list items. I stumbled upon this code that seems to do the trick. $(document).on('click',function() { ...

tracking scroll position within div on main page

I have a div tag enclosed within a content tag due to the implementation of a masterpage containing the forms and body tags. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <div id="xxx" style="overflow:s ...

Find similarities between 2 observable arrays and store them in a new array using knockout data binding

There are three observable arrays set up as follows: a [1,3] b [ {"ID": 1, "Val": "Value1"}, {"ID":2, "Val":"Value2"}, {"ID":3, "Val":"Value3"}] c [] The goal is to compare array a with the IDs of elements in array b and then push the entire value of arr ...

Ways to extract input values from a specific row in a textbox as users input data

On a button click, I am dynamically adding data to an HTML table using the loadbooks function. When the user clicks on the button, the table is populated with data. <button id="button" onclick="loadbooks()"></button> function loadbooks() { ... ...

How can we nest a div within the outermost parent element?

Consider a scenario where there are 3 different divs named grandParent, Parent, and Child. Although the parent's tag is placed inside the grandParent, due to the use of position: absolute; property, the parent ends up being displayed outside the grand ...

Is there a way to showcase the generated results on a graph after the user presses the submit button?

I've been working with to generate a bar chart. Currently, when the user clicks 'submit', the input numbers are shown in a graph on http://jsfiddle.net/jx9sJ/5/. Now, I want to make some changes. I am attempting to send the input numbers t ...

Utilize res.render in Node.js to pass multiple data arrays to the view

I am facing an issue with populating two separate selects in my view with different arrays. Can anyone guide me on how to pass two distinct JSON objects using res.render? I have attempted the method below without success. const result1 = {data1: "val ...

I'm experiencing very slow page load times in dev mode with Next.js (30s+). What could be the reason behind this sluggishness?

QUESTION: Encountering a similar issue (but with different files): https://github.com/vercel/next.js/discussions/17977 I've already tried all the suggestions provided in that discussion. This is what the page load process looks like in development ...

JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays? The structure of my array is as follows: tabs=[ {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: ...

Accurate representation of a JavaScript object using Node.js Express

I have a certain structure that I need to display on my JADE page, so I created a JSON-like object to store the data. This is how the JSON object looks like : var dataSet1 = { meta: { "name": "Some text", "minimum": mini_2, "ma ...

Fill a Bootstrap Table with information obtained from a JSON file source

My journey into the world of bootstrap and json files has hit a roadblock, and I need some help with the following issue: Here is a snippet of my code: <div class="container"> <h1 class="text text-success text-center ">Kontoauszug</ ...

Using a jquery function within a Laravel view

I am trying to retrieve a selected item from a dropdown menu using jQuery and then redirect it to a controller function. This function will return some data to be displayed based on the selected item. I could really use some assistance with this. Here is m ...

The JavaScript for loop using .appendChild() is inserting the values of the final object, represented as [object object], into the HTML document

$(document).ready(function () { GetDetails(); }); function GetDetails() { let albumlist = document.getElementById("album-list"); $.ajax({ url: '/Store/browseajax', type: 'GET', data: { id: '@ ...