Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter.

Progress So Far:

  1. I am able to retrieve values from all inputs, including the name and asc/desc requests
  2. I can return results based on the name input

What I Need:

  1. Add the ability to sort results using the asc / desc request

Code:

HTML:

<form [formGroup]="filterForm" (ngSubmit)="search(column.real_name)">
  <div class="card search-box p-2">
    <div class="mb-2">
      <label for="">Search By {{ column.name }}</label> <br>
      <input nz-input formControlName="formInput" placeholder="Type here..." />
    </div>

    <div class="mb-2">
      <label for="sort">Sort Order</label> <br>
      <nz-select ngModel="none" formControlName="formSort" class="text-left mr-2" style="width:100%;">
          <nz-option nzValue="none" nzLabel="None"></nz-option>
          <nz-option nzValue="asc" nzLabel="Ascending"></nz-option>
          <nz-option nzValue="desc" nzLabel="Descending"></nz-option>
      </nz-select>
    </div>

    <div class="mb-2">
      <label for="op">Filter Column</label> <br>
      <nz-select ngModel="contains" formControlName="formColumn" class="text-left mr-2" style="width:100%;">
          <nz-option nzValue="contains" nzLabel="Contains"></nz-option>
          <nz-option nzValue="like" nzLabel="Like"></nz-option>
      </nz-select>
    </div>
    <button type="submit" class="btn btn-warning w-100 mt-2"><i class="fe fe-search"></i> Search</button>
  </div>
</form>

Script: (commented)

import { FormBuilder, FormGroup } from '@angular/forms';

filterForm: FormGroup

constructor(
  public formBuilder: FormBuilder,
) {
   this.filterForm =  this.formBuilder.group({
     formInput:  [null, Validators.required],
     formSort:  [null, Validators.required],
     formColumn:  [null, Validators.required],
   })
}

search(column): void {
  const filterFormData = this.filterForm.value;

  // values
  console.log('formInput: ', filterFormData.formInput); // Already implemented (name input)
  console.log('formSort: ', filterFormData.formSort); // Now I want to implement this value
  console.log('formColumn: ', filterFormData.formColumn);
  console.log('formColumnName: ', column);

  this.visible = false;

  // return results in table (currently only name input is presented)
  this.listOfData = this.listOfData.filter((item: DataItem) =>
    item[column].toLowerCase().indexOf(filterFormData.formInput.toLowerCase()) !== -1
  );
}

Answer №1

If you want to implement sorting functionality in addition to filtering, you can create a compare function and pass it to the native sort function. Here's how you can do it:

search(column): void {
  const filterFormData = this.filterForm.value;

  // Display values
  console.log('formInput: ', filterFormData.formInput);
  console.log('formSort: ', filterFormData.formSort);
  console.log('formColumn: ', filterFormData.formColumn);
  console.log('formColumnName: ', column);

  this.visible = false;

  // Filtering based on user input
  this.listOfData = this.listOfData.filter((item: DataItem) =>
    item[column].toLowerCase().indexOf(filterFormData.formInput.toLowerCase()) !== -1
  );

  // Sorting functionality based on formSort value
  if (filterFormData.formSort === "asc") {
    const sortAsc = (a,b) => a[column] < b[column] ? -1 : a[column] > b[column] ? 1 : 0;
    this.listOfData.sort(sortAsc);
  } else if (filterFormData.formSort === "desc") {
    const sortDesc = (a,b) => a[column] < b[column] ? 1 : a[column] > b[column] ? -1 : 0;
    this.listOfData.sort(sortDesc);
  }
}

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

Utilizing Node.js and express to promptly address client requests while proceeding with tasks in the nextTick

I am looking to optimize server performance by separating high CPU consuming tasks from the user experience: ./main.js: var express = require('express'); var Test = require('./resources/test'); var http = require('http'); va ...

When using jQuery, remember to encode square brackets in order to target specific

Imagine an input element <input id="meta[152][value]" type="text" /> In this case, the input field is created on-the-fly. I must choose that particular field. That's why I used, alert($('#meta[152][value]').val()); However, it appe ...

Is Operator Overloading supported in Typescript?

I'm curious about whether operator overloading is supported in typescript. If it does exist, I'd be happy to provide an example or a link for you to explore further. ...

Having trouble retrieving returned data after refetching queries using Apollo and GraphQL

I am able to track my refetch collecting data in the network tab, but I am facing difficulty in retrieving and using that data. In the code snippet below where I am handling the refetch, I am expecting the data to be included in {(mutation, result, ...res ...

What is the best way to combine relative paths or create distinct identifiers for SVG files located within multiple layers of folders

I have a collection of icons exported from "Figma" organized in folders, and I'm using grunt-svgstore to create a sprite sheet. However, the result contains duplicated IDs even after trying 'allowDuplicateItems: false' and 'setUniqueIds ...

What is the best way to create a JavaScript button that can be clicked to increase a variable by 1?

I am curious to know how you can create a button that appears on an empty HTML canvas and, when clicked, adds +1 to a variable. I am working on this JavaScript code within an HTML text file which will later be saved as an HTML file. Please ensure that th ...

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...

Strategies for disabling middle mouse button default behavior in Vue

When I use @click.middle.stop.prevent="test", the default scroll wheel still shows up despite it detecting the middle mouse click and calling my function. Is there a way to prevent this from happening? ...

Deriving union type in Typescript from values within a module or object

I'm trying to find a method similar to keyof typeof myModule in typescript. However, instead of a union of key strings, I need a union of the value types. I have a module with an increasing number of exports - myModule.ts: export const Thing1; expor ...

Dragging items in the horizontal list of Knockout-Sortable causes them to be pushed vertically

For my application development using knockout.js, I am implementing knockout-sortable to create drag-and-drop sortable lists. The setup involves a vertical list with each item containing a horizontal list. While the vertical lists are functioning properly, ...

Move a div by dragging and dropping it into another div

Situation Within my project, there is a feature that involves adding a note to a section and then being able to move it to other sections, essentially tracking tasks. I have successfully implemented the functionality to dynamically add and drag notes with ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...

jQuery is unable to manipulate newly added DOM elements that have been loaded via AJAX

Having trouble with jquery ajax. Unable to interact with newly added element through ajax. Code snippet: $(".yorum_input").keypress(function(e) { if (e.keyCode == 13) { e.preventDefault(); var alt_id = $(this).attr('yorum_id'); va ...

Is there a way to establish communication between two ReactJS components by utilizing Jotai?

I am facing a problem with 2 reactjs files: Reports.js (handles report requests and displays results) AuthContext.js (maintains communication with backend server through a socket connection) The user initially visits the report page generated by Reports. ...

TypeScript error: Unable to locate namespace 'ng'

I am attempting to utilize a tsconfig.json file in order to avoid having /// <reference tags at the beginning of multiple files. However, I keep encountering this error: [ts] Cannot find namespace 'ng'. any Here is my configuration within ...

Determining the class condition using AngularJS ng-class

I am working with an HTML element that contains AngularJS directives: <div class="progress"> <span ng-repeat="timeRangeObject in timeRangeObjects" style="width: {{timeRangeObject.percentage}}%" ...

Executing jQuery callback functions before the completion of animations

My issue revolves around attempting to clear a div after sliding it up, only to have it empty before completing the slide. The content I want to remove is retrieved through an Ajax call. Below you will find my complete code snippet: $('.more& ...

Discover which references are yet to be resolved within a tsx file

I have been tasked with developing a custom builder for a web application. The challenge now is to automatically detect imports in the code so that the right modules can be imported. My current solution involves traversing the AST of the scripts, keeping ...

Error: Unable to execute candidate.toLowerCase as a function

Encountering the following errors: `Uncaught TypeError: candidate.toLowerCase is not a function. I am utilizing the AutoComplete API within Material UI, however, when I search in the input field, it leads me to a blank page. https://i.sstatic.net/Yv3ZU.pn ...