What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem.

To access the code, click here: https://stackblitz.com/edit/angular-ivy-87hi8i?file=src%2Fapp%2Fapp.component.html

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;
      }
    });
  }

markup

<tr>
<th *ngIf="!isEdit">Edit</th>
<th [ngClass]="{pointer: true, active:column=='first_name',desc:isDesc, asc:!isDesc}"
(click)="sort('first_name')">First Name</th>
<th [ngClass]="{pointer: true, active:column=='last_name',desc:isDesc, asc:!isDesc}"
(click)="sort('last_name')">Last Name</th>
<th>Email</th>
<th>Gender</th>
<th>DOB</th>
<th>Impact</th>
<th>Score</th>
<th [ngClass]="{pointer: true, active:column=='dl',desc:isDesc, asc:!isDesc}" (click)="sort('dl')">
DL</th>
<th [ngClass]="{pointer: true, active:column=='co_score',desc:isDesc, asc:!isDesc}"
(click)="sort('co_score')">DL Score</th>
<th></th>
</tr>

Answer №1

Your method of sorting is declared as follows:

 this.allUser.sort(function(
      a: { [x: string]: number },
      b: { [x: string]: number }
    )

This implies that all objects in your array have keys that return numbers.

When sorting by the first_name property, it encounters values like A Male when accessing a['first_name'], which is not a number, creating a logical issue. However, JavaScript can still sort strings numerically in runtime.

On the other hand, sorting by the dl property poses another problem since it doesn't exist in your objects. This results in comparing undefined with undefined (a['dl']), leading to no actual sorting taking place.

To address this, ensure that your objects contain a value for the dl property if you intend to perform sorting based on it.

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

Is there a more effective method for detecting changes in a class variable in JavaScript, aside from using setInterval()?

Is there a more readable way to monitor changes of a class variable from its instance? Although I can use setInterval() to achieve this, the code becomes quite difficult to read. let calibrator = new Calibrator("hardwareName"); calibrator.connect(); let ...

What is the process for passing input values to a dynamic Angular component?

https://i.sstatic.net/hghse.png My goal is to develop a dynamic filtering system where users can specify multiple attributes and their corresponding values to filter a list of components. The dynamically added component includes two dropdown menus: one fo ...

Testing the creation of elements dynamically with jestLooking into jest for dynamically adding

Attempting to test a dynamic element using TypeScript, but struggling to understand the process. Can anyone offer guidance? Below is the TypeScript file: export default class MyClass { constructor(){ this.render(); } render() { ...

Uncover the valuable information within a string using regex in JavaScript

I am looking for a solution to extract key values from a string that looks like this: <!-- Name:Peter Smith --><!-- Age:23 --> My goal is to create a standard function that can extract any value needed. The function call would be something lik ...

What is the best way to overlay an SVG line on top of a CSS style?

Is there a way to make SVG lines appear on top of CSS-styled elements in my HTML file? I have a white background SVG created with JavaScript using d3, and I am adding CSS-styled rectangles on top of it. However, I also want SVG lines (created with JavaScri ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

Utilizing Angular Observables to Consume a REST API

Recently, I developed a REST API using Flask. However, when I tried to integrate it with my Angular web app, I encountered some errors. Despite following the steps outlined in the official documentation: https://angular.io/tutorial/toh-pt6 getBills(): voi ...

Organizing a series of objects into groups of four for processing

I have a task of organizing an array of objects that represent game players by assigning each player to a group number based on their current group value. The challenge is to ensure that each group has as close to four players as possible, while also acco ...

Guide to embedding bootstrap.min.js into ember-bootstrap extension

I'm currently experiencing an issue with the ember-bootstrap plugin. Following the instructions on their setup page at , I downloaded and installed it. Once I began working on the Navbar, I encountered a problem. The Hamburger menu, which is supposed ...

Effortlessly navigate between Formik Fields with automated tabbing

I have a component that validates a 4 digit phone code. It functions well and has a good appearance. However, I am struggling with the inability to autotab between numbers. Currently, I have to manually navigate to each input field and enter the number. Is ...

Fixing TypeError in React App: How to Resolve the "Cannot read property 'prototype' of undefined" Issue

I am completely new to JavaScript and I am struggling to understand the error that keeps popping up. After doing some research, it seems like the error could be due to a poorly written function or something along those lines. Here are the classes involved ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...

Positioning of the dropdown in Material UI AutoComplete menus

Is there a way to turn off autocomplete auto position? I would like the autocomplete options to always appear at the bottom. Check out this link for more information! ...

Angular 5's recursive directives in dynamic modules without any circular dependencies

I've been experimenting with loading dynamic templates into my Angular 5 app. My first attempt was following the examples in the official Angular documentation, but I quickly realized that they only cover loading static components dynamically. Next, ...

Using React to iterate through the child components of the parent

I have created a component that can accept either a single child or multiple children. Here is an example with multiple children: <SideDataGridItem> <div id='top'> <div>A1</div> <div>B1</div> ...

Guide to using AJAX to send a select tag value to a PHP script on the current page

Issue I am facing a problem where I need to utilize the select tag in order to choose a value and then send that value via an ajax call to a PHP script embedded within the same page. In my code, I have implemented the select tag and upon selecting a valu ...

How to retrieve the data from a PHP file using Angular 4 CLI?

Is there a way to retrieve the response from a PHP file using Angular 4? If the PHP file is placed in the assets folder, the GET request will identify the file and proceed to download its content. For example: headers: Headers ok: true status: 200 status ...

Steps to update the toolbar color of Mui DataGrid

Check out this unique custom Toolbar I created specifically for Mui dataGrid function CustomToolbar() { return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensit ...

What is the most effective method for distributing TypeScript functions that are used by services and span multiple components?

I have a set of TypeScript functions that are currently scattered across components. These functions are being duplicated unnecessarily, and I am looking for a way to centralize them so all components can access them without redundancies. Since these fun ...

Material UI Snackbar background color not able to be changed

Currently, I'm working on an ErrorHandler component in React.JS that displays a Material UI Snackbar whenever it catches an error. The issue I'm facing is trying to change the background color of the Snackbar to red, which seems to be problematic ...