My preference is to arrange strings in a numerical fashion

Trying to implement a sorting function with an arrow button that inverts for exam scores

Struggling to get the correct sorting order

The current code snippet results in

[N/A, N/A, 99%, 90%, ... 20%, 100%, 10%, 0%]

being sorted as

[0%, 10%, 100%, 20%, ... 90%, 99%, N/A, N/A]

and vice versa

      // Score Sort
      if(this.scoreSort && this.sortColumn === 'Score'){
        const sortedData = data.sort((a, b) => {
          const titleA = a.Score ? a.Score : '';
          const titleB = b.Score ? b.Score : '';
          if(titleA > titleB){ return this.scoreSort ?  1 : -1 }
          if(titleA < titleB){ return this.scoreSort ? -1 :  1 }
          return 0;
        });
        return sortedData;
      } if(!this.scoreSort && this.sortColumn === 'Score') {
        const sortedData = data.sort((a, b) => {
          const titleA = a.Score ? a.Score : '';
          const titleB = b.Score ? b.Score : '';
          if(titleA > titleB){ return this.scoreSort ?  1 : -1 }
          if(titleA < titleB){ return this.scoreSort ? -1 :  1 }
          return 0;
        });
        return sortedData;
      }

Is there a way to sort them like the array below?

[100%, 99%, 90%, ... 20%, 10%, 0%, N/A, N/A]

to be displayed as

[0%, 10%, 20%, ... 90%, 99%, 100%, N/A, N/A]

and vice versa

Answer №1

To achieve numeric sorting in JavaScript, you can utilize the localeCompare method with the numeric: true option. Here's an example:

const input = ["N/A", "N/A", "99%", "90%", "20%", "100%", "10%", "0%"],
      sorted = input.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))

console.log(sorted)

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

Working with MongoDB collections in JavaScript to extract and manipulate array data

I have successfully parsed this array using a for loop You can view the results in the console log below. https://i.sstatic.net/zxBna.png When handling role_code in JavaScript, the following code snippet can be used: for (doctor in data.user.userType){ ...

What is the best way to transfer item information from Flatlist within a React Native application?

I am a newcomer to react. In my App.js file, I have the main code, and in another folder, there is a lists.js file that contains the list data. I successfully import the list from lists.js into my App.js file. Now, I want to add an onPress action to the ...

What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file: <!DOCTYPE html> <!-- --> <html> <head> <script src="java_script.js"></script> <link rel="stylesheet" type="text/css" href="carousel.css"> & ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

How to efficiently load SharePoint profile images in an asynchronous manner

Currently, I am working within a SharePoint farm that has User Profiles enabled. Within this environment, we are developing a community feature that includes a profile wall showcasing all members of the community. My task involves retrieving and displaying ...

Update the webpage post a database entry without relying on the setTimeout() function in Javascript

Is there a method to automatically refresh the page after a new entry in the database without relying on Javascript's setTimeout or setInterval functions? Could an AJAX function or a MySQL function accomplish this task instead? Must we continuously ...

Edge browser: Disable Ctrl + left click functionality

Can I stop Microsoft Edge from automatically opening a link in a new tab when I use Ctrl + Left click? I want to trigger my own event instead of the default behavior caused by Ctrl + Left click in Edge browser. ...

Encountering a problem with the mock object in Angular 11 unit testing when converting a JSON object to a TypeScript interface

Within my Angular 11 application, I am working with a JSON response and have defined an interface to match the structure of this JSON object. The JSON object looks like this: { "division": { "uid": "f5a10d90-60d6-4937-b917- ...

Customize the border width and color of a specific column in HighCharts based on dynamic data

I am looking to dynamically change the border width and color of only one column in a basic column chart. Here is an example: var chartingOptions = { chart: { renderTo: 'container', type: 'column' }, xAxis: { categories: [ ...

How to effectively manipulate nested arrays in JavaScript without altering their references

Welcome everyone, I've been working on a project using next.js and I've encountered an issue with filtering posts. The filter function works perfectly when the posts are in a simple array like ObjChild. However, I have another section on my site ...

When using the `array.join` method with nested arrays, it does not automatically include spaces in the output

function convertArrayToString(arr) { // Your solution goes here. let str = arr.join(", "); return str; } const nestedValues = [5, 6, [7], ["8", ["9", ["10" ]]]]; const convertedString = convertArrayToString(nestedValues); console.log(convertedString ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...

Utilize AJAX/JS and Django to seamlessly upload files

This is the form for my popup window. <div class="popup media-upload-form"> <div class="border cf"> <div class="close">X</div> </div> <form class="cf" action="" method="POST" enctype="multipart/form-data"> ...

Is there a way to dynamically insert objects into an array from an ajax json request, in order to iterate through them later on?

I have a current code where I am trying to utilize data to create a new information window from the Google Maps API dynamically. Currently, I am pushing objects of different data types into an array, but I believe that might be the only issue here. How c ...

Tips for centering or aligning a component to the right using Material UI?

Is there an efficient method to align my button to the right of its parent in Material UI? One approach could be using: <Grid container justify="flex-end"> However, this would also require implementing another <Grid item />, which m ...

Integrating a subcategory instance of an abstract class in TypeScript

I am curious about how to effectively implement the example below. I am working on abstracting some fundamental functionality of a House. The scenario I encountered is as follows: Imagine there is an abstract Animal class that is extended like this: abst ...

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

Utilizing jQuery Ajax to simultaneously insert and fetch data upon submission, with the fetched data automatically posted on the URL opened by window.open

When the #user_form_cert is submitted, the data will be inserted and fetched at the same time. I have used this code where the insert works fine but the fetch is not working and shows undefined on the window.open URL. $(document).on('submit', &a ...

Node.js application hosted on Google App Engine is not including cookies in the HTTP header

I have successfully deployed a Node app on Google App Engine, where I am managing authorization through sessions in the backend. My postgres datastore is handled using connect-pg-simple, and I can confirm that sessions are being stored in the database. // ...