The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercase and lowercase characters, as well as numerical values and special characters like dollar signs.

For example:

$110, $12, $24000, $2500, $3

Instead of being sorted as:

$3, $12, $110, $2500, $24000

Or for a column with mixed case elements, it currently sorts like:

Apple, Banana, Dog, ant, candy

When it should ideally be:

ant, Apple, Banana, candy, Dog

The current logic also causes issues when sorting numbers like - 112,12,141,21,32,345,35;

However, it should display them as: 12,21,32,35,112,141,345;

Here is the snippet of code I have been using:

const [sort, setSort] = usestate("asc")
const onSort = (obj: string) => {
    
    if (sort === "asc") {
      const tableEl= [...tableItem].sort((a: any, b: any) => {
        if (a[obj].split('/').reverse().join() > b[obj].split('/').reverse().join()) return 1;
        else if (b[obj].split('/').reverse().join() > a[obj].split('/').reverse().join()) return -1;
        else return 0;
        
      });
      setTableState({
        ...tstate,
        tableItem: tableEl,
      });
      setSort("dsc")
    }
    if (sort === "dsc") {
      const tableEl= [...tableItem].sort((a: any, b: any) => {
        if (b[obj].split('/').reverse().join() > a[obj].split('/').reverse().join()) return 
          1;
        else if (a[obj].split('/').reverse().join() > b[obj].split('/').reverse().join()) return -1;
       
        
      });
      setTableState({
        ...tstate,
        tableItem: tableEl,
      });
      setSort("asc")
    }
  };

Answer №1

To ensure case sensitivity is considered, use the localCompare method. When checking for numbers, utilize the isNaN method.

function compareValues(x, y) {
    if ( isNaN(Number(x) || isNaN(Number(y))) {
        return y.localeCompare(x)
    } else {
        if (Number(x)>Number(y)) return 1
        else if (Number(x)<Number(y)) return -1
        else return 0
    }
}

Implement this function within the sort method like so:

[...stateData.items].sort(compareValues)

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 preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

What could be causing the remove attribute API to not function properly only for the "is" attribute?

var divElement = document.createElement("div"); var innerHTMLText = "<div id='issue' is='if'> some content </div>"; divElement.innerHTML = innerHTMLText; document.body.appendChild(divElement); var newDivElement = document.qu ...

The function failed to obtain JSON data from the generated URL

I want to fetch the latest local weather details using a weather API. Below is the code I am working with: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> function generateUrl() { var ap ...

Why does Typescript's 'await' seem to not wait as expected?

Apologies for the rookie mistake, I am currently transitioning from a C# background to Ionic, which may be causing some confusion on my end. I'm working on retrieving a stored token from Ionic storage but I'm struggling with understanding promise ...

What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data? I have attempted to use a recursive function, but it seems to be calling infinitely. For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/ for(var ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...

Connect ngOptions to an array beyond the current scope

Can the ngOptions be bound to a value that is not within the $scope? I have enums that will be generated as JavaScript code. These enums are not currently part of "the angular domain", but I want to bind an ngOptions to one of the arrays without manually ...

Maintain the chosen month in every dropdown toggle div in angular 4

While displaying data using toggle options, I am facing an issue where if I click on a different month, all other greyed out headers are displaying the previously selected values. I am trying to figure out a way to keep the value under Selected month as i ...

Data sent through AJAX messaging is not being acknowledged

I recently made an AJAX request and set it up like this: $.ajax({ data : { id : 25 }, dataType : 'json', contentType : 'application/json; charset=utf-8', type : 'POST', // the rest of the ...

What is the best way to keep track of the number of checked checkboxes and add them to a separate div?

I need to select multiple checkboxes from different sections, count them, and then append the same number of sections to another div. ...

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...

Inheritance of Generic Types in TypeScript

Could someone assist me in understanding what is incorrect with the code snippet provided here? I am still learning Typescript. interface ICalcValue { readonly IsNumber: boolean; readonly IsString: boolean; } interface ICalcValue<T> ex ...

Developing a dynamic row that automatically scrolls horizontally

What is the best method for creating a div box containing content that automatically slides to the next one, as shown by the arrows in the picture? I know I may need jquery for this, but I'm curious if there's an alternative approach. oi62.tinyp ...

Is there a way to imitate the typeof operation on an object in TypeScript?

Today's challenge is a strange one - I've encountered a bug where the code behaves differently if typeof(transaction) returns object instead of the object name. To work around this issue, I introduced a new parameter called transactionType to my ...

Tips to Avoid Multiple Executions of Javascript Code due to Caching

When I make a request to my Asp.net-MVC application, it returns a partial-view. public ActionResult AccountDetails() { return PartialView("~/Views/partials/Account/Details.cshtml"); } To load the partial view in my form, I use the following ...

"When attempting to pass a string into the res.send() method in Node.js, undefined

As a new Node.js user, I'm attempting to send data back to the browser by utilizing a function called load_blocks() from an external file that I created, and then calling it with res.send(). I currently have two basic files in my setup: The first on ...

Is it feasible to set a default value in an HTML input field that is not editable using JavaScript?

Is there a way to set a default value in an input field of HTML that is not editable, and then allow users to add additional text to it? For example, having 'AB' as the default and uneditable starting characters, followed by any numbers such as A ...

Tips for transferring a value from a view to a controller using AngularJS

I've created a controller that dynamically generates tables based on data retrieved from the backend using $http.get. I'm wondering how I can pass a value to this controller from the view, indicating which URL it should use to fetch the data for ...

A more efficient method for tallying values within an object (JavaScript, React)

Is there a more efficient way to determine the count of items with a specific key/value pair in a React state? When the list is large, this method may become a bottleneck. To illustrate the question, consider the following simplified example: class App ...

Module for managing optional arguments in Node.js applications

I'm on the hunt for a Node.js module that can effectively manage and assign optional arguments. Let's consider a function signature like this: function foo(desc, opts, cb, extra, writable) { "desc" and "cb" are mandatory, while everything else ...