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

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Using the Gmail API to retrieve the access token details by extracting the "code" parameter from the URL of a pop-up window

I am currently in the process of authenticating Gmail using OAuth2 for my web application. Upon receiving a URL from the server, the client opens a pop-up window with the following code: var win = window.open(data.google_oauth_url, `<h1>Gmail ...

Is there a workaround for utilizing reducer dispatch outside of a React component without relying on the store?

Recently, I implemented a reducer in my project that involves using react, typescript and nextJS. I am wondering if there is a method to trigger the reducer outside of a react component, such as from an API service. While searching for solutions, most re ...

Squashing the `require()` method in nwJS using emberJS

I am facing an issue with my nwjs application that connects to a web address hosting an ember application. I need to access the node context within the ember application to determine the user's operating system for updating purposes. I attempted to do ...

What is the best way to incorporate this code snippet into an object's value?

Is there a way to merge the headStyles object into the headText object? I have already injected the headStyles object into headConfig. import { makeStyles } from '@material-ui/core' const headStyles = { backgroundColor:'green', ...

Explore additional sub-categories by clicking on them with the help of jQuery or alternate techniques

I am currently working on a Magento store that has Categories with an overwhelming amount of sub-categories, taking up almost half of the page. I want to enhance user experience by implementing a feature that displays a "Load more" button when there are mo ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Transferring object information to Backand using Ionic 2

I have developed a signup page using Ionic 2. In this signup page, I have included a dropdown menu for users to select their blood type. However, I am facing an issue where the selected blood type is not being sent to the Backand database as expected. I&ap ...

The program experienced an issue with TypeError: Attempting to access properties of an undefined variable ('_id')

I am attempting to show a data entry (with a unique id) in Angular, but I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading '_id') The service for retrieving the specific id is defined as: g ...

What is the best way to execute a function individually for every tag within a vue.js application?

I'm currently exploring the world of Vue JS and I thought it would be interesting to experiment with something new. Sometimes looking at the code first makes understanding it much easier than a lengthy explanation. Check out this code snippet on jsFi ...

I can't seem to establish a connection with my MongoDB Atlas cluster. I encountered the MongooseError, which is as follows:

Error [MongooseError]: The uri parameter for the openUri() method needs to be a string but is currently set as "undefined". Please ensure that the first parameter for mongoose.connect() or mongoose.createConnection() is a valid string. const express = r ...

Issue with IE11: the selected list is not displayed when using the <s:optiontransferselect> tag

When moving groups from left to right in the s:optiontransferselect for selectedGrps and unselectedGrps, the SelectedGroups list is showing as null on form submission in IE11. However, in Chrome and Mozilla, it functions correctly. Any advice would be grea ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

Having trouble sending specific data using the jQuery Form Plugin ajaxForm feature

Currently, I am utilizing two jQuery plugins: plupload and jQuery Form Plugin ajaxForm. Everything is functioning well except for one issue: I am unable to send the file.name (using ajaxForm) of a previously uploaded file with plupload. To elaborate more ...

What is the method for triggering two actions within a single linked tag?

I have a link tag structured like this: <a href="<?php echo base_url().'dashboard' ?>" class="check_session">Home</a> Upon clicking the "Home" link, it should navigate to the dashboard. At the dashboard page, I want to check i ...

Are trailing commas or missing keys acceptable in JavaScript object notation?

I have created a code generator and I am contemplating whether or not to address the issue of the extra comma at the end. While Internet Explorer seems to ignore it, I want to ensure cross-browser compatibility and generate valid code. function init() { v ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

Customizing the default settings of a d3 funnel chart

I recently used the following link to create a funnel chart using D3: jakezatecky/d3-funnel Everything was working perfectly. However, I wanted to adjust the block heights in proportion to their weight as mentioned in the tutorial by changing the D3 defau ...

Tips for transferring parameters to functions within middleware

Attempting to pass a parameter to a middleware has presented some challenges for me. Within the routes' handler, I have the following function: router.get('/users', auth.required, userController.findAll); This function then leads to the a ...

An error was encountered in the index.js file within the app directory when running the webpack

Recently, I was told to learn react.js even though my knowledge of javascript is limited. Nevertheless, I decided to dive in and start with a simple "Hello World" project. Initially, when I used the index.js file below and ran webpack -p, everything worke ...