Arranging Objects by Alphabetical Order in Typescript

I am struggling with sorting a list of objects by a string property. The property values are in the format D1, D2 ... D10 ... DXX, always starting with a D followed by a number. However, when I attempt to sort the array using the following code snippet, it does not sort in the expected ascending order:

this.list = v.sort((a, b) => a.property.localeCompare(b.property));

The current result of the sorting looks like this:

Index Property value
0 D10
1 D11
2 D3
3 D5
... ...

I want the sorting results to look like this instead:

Index Property value
0 D3
1 D5
2 D10
3 D11
... ...

Answer №1

Your data consists of strings, which means they are organized in lexicographical order lexicographically

If you want to arrange them based on the numerical part of the string, you need to first extract the number from each string for a proper numeric sort

extractNumber(stringValue: string) {
  // Assumes all strings have a single character 'D' at the beginning
  return Number(stringValue.slice(1))
}

this.dataList = values.sort((x, y) => extractNumber(x.property) - extractNumber(y.property));

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

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

What is the best way to create an instance method in a subclass that can also call a different instance method?

In our programming project, we have a hierarchy of classes where some classes inherit from a base class. Our goal is to create an instance method that is strongly-typed in such a way that it only accepts the name of another instance method as input. We d ...

Following an update from typescript version 2.3.4 to 2.4.2, I encountered a compilation error stating, "The type definition file for 'reflect-metadata' cannot be found."

Recently, I encountered an issue with my React / Mobex application written in TypeScript and built by Webpack 1. Upon updating the TypeScript version from 2.3.4 to 2.4.2, an error started occurring. The error message reads: ERROR in C:\myproject&bsol ...

Tips for effectively handling requestAnimationFrame

I created a unique function that both scrambles and translates text. The functionality is smooth if you patiently wait for the animation to finish before moving the mouse over to other elements. However, if you try to rush through to the next one, the prev ...

Retrieving data from an API using VUEJS3 and Typescript

I am facing an issue with displaying data in my template. When I try to do so, the screen remains blank. I am using Vue.js 3 with TypeScript and I am fairly new to this technology. <template> <div> <img :src="datas[0].imag ...

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

Creating PropTypes from TypeScript

Currently in my React project, I am utilizing TypeScript along with PropTypes to ensure type checking and validation of props. It feels redundant to write types for both TypeScript and PropTypes, especially when defining components like ListingsList: inte ...

Tips on forming an Array using numerical values

I have a query regarding the generation of an array based on a user-specified number. For instance, if the user requests the number '5', the array sequence should look like this: [001,002,003,004,005) I am working in Laravel and have been attem ...

Angular 2: Sending an HTTP GET request with custom headers and parameters

I have been encountering difficulties while attempting to retrieve data from a Stardog triple store into Angular. Despite successfully accessing the service using curl with matching headers and parameters, I am unable to replicate this functionality with ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

Looking to create a sophisticated list of objects using Python and lists?

I am seeking assistance in generating data that follows specific rules and a unique structure. I am unsure of the approach to take, so any help would be greatly appreciated. Here are the two lists: categories = [ 'fruits', 'meats&apo ...

Issue with action creator documentation not displaying comments

We are exploring the possibility of integrating redux-toolkit into our application, but I am facing an issue with displaying the documentation comments for our action creators. Here is our old code snippet: const ADD_NAME = 'ADD_NAME'; /** * Se ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Leveraging Angular 4-5's HttpClient for precise typing in HTTP requests

Utilizing a helper service to simplify httpClient calls, I am eager to enforce strong typing on the Observable being returned. In my service where I utilize the api Service and attempt to obtain a strongly typed observable that emits: export class ApiU ...

cookies cannot be obtained from ExecutionContext

I've been trying to obtain a cookie while working with the nestjs and graphql technologies. However, I encountered an issue when it came to validating the cookies by implementing graphql on the module and creating a UseGuard. It was suggested that I ...

Showing an image on an ajax request

I have developed a unique user search engine that not only shows the user's details but also their profile picture. index.php if (account !="") { $.ajax({ url:"profile.php", method:"POST", ...

Modify the array output so that it no longer contains brackets

After transforming a sparse dictionary into an array using (np.asarray), I created a function that utilizes this array to calculate a formula. However, the output generated includes double brackets instead of the desired single bracket format. For example, ...

What is the correct way to bring in a utility in my playwright test when I am working with TypeScript?

I am working on a basic project using playwright and typescript. My goal is to implement a logger.ts file that will manage log files and log any logger.info messages in those files. To set up my project, I used the following commands and created a playwri ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

"Dealing with cross-origin resource sharing issue in a Node.js project using TypeScript with Apollo server

I am encountering issues with CORS in my application. Could it be a misconfiguration on my server side? I am attempting to create a user in my PostgreSQL database through the frontend. I have set up a tsx component that serves as a form. However, when I tr ...