Arranging Alphanumeric Characters in Typescript

Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b']

Expected output after sorting -> const s = ['2.1.a', '2.1.b', '2.1.1.a', '2.1.1.b', '2.1.1.c', '2.1.1.d', 'A2.1', 'A2.2']

Output after sorting using the methods below -> const s = ['2.1.b', '2.1.a', '2.1.1.d', '2.1.1.c', '2.1.1.b', '2.1.1.a', 'A2.1', 'A2.2']

Below are the angular methods attempted to sort and the question of what may be wrong with the code:

private REGEXP_SPECIAL_CHAR = /^[A-Za-z]\d$/;

bubbleSort(collection: any[], property: string = 'code'): any[] {
        let memo = null;

        if (!collection.length) { return collection; }

        for (let outer = 0; outer < collection.length; outer++) {
            for (let inner = 0; inner < collection.length; inner++) {
                if (this.compare(collection[outer][property], collection[inner][property]) === -1) {
                    memo = collection[outer];
                    collection[outer] = collection[inner];
                    collection[inner] = memo;
                }
            }
        }

        return collection;
    }
    private compare(v: any, w: any): number {
        const vCollection = v.split('.');
        const wCollection = w.split('.');
        const depth = Math.min(vCollection.length, wCollection.length);
        let res = 0;

        for (let i = 0; i < depth; i++) {
            const vElement = vCollection[i];
            const wElement = wCollection[i];
            const shouldCompareNumbers = !isNaN(Number(vElement)) && !isNaN(Number(wElement));
            const shouldCompareChars = this.isSpecialSymbol(vElement, wElement) || (!isNaN(Number(vElement)) && !isNaN(Number(wElement)));

            if (shouldCompareNumbers) {
                if (Number(vElement) < Number(wElement)) {
                    res = -1;
                    break;
                } else if (Number(vElement) > Number(wElement)) {
                    res = 1;
                    break;
                }
            } else if (shouldCompareChars) {
                if (vElement < wElement) {
                    res = -1;
                    break;
                } else if (vElement > wElement) {
                    res = 1;
                    break;
                }
            } else {
                if (vElement < wElement) {
                    res = 1;
                    break;
                } else if (vElement > wElement) {
                    res = -1;
                    break;
                }
            }
        }

        if (res === 0) {
            // check depth
            if (vCollection.length > wCollection.length) {
                res = 1;
            } else if (vCollection.length < wCollection.length) {
                res = -1;
            } else {
                res = 0;
            }
        }
        return res;
    }

    private isSpecialSymbol(v: string, w: string): boolean {
        return this.REGEXP_SPECIAL_CHAR.test(v) || this.REGEXP_SPECIAL_CHAR.test(w);
    }

Answer №1

If all of your numbers consist of the same digits, you have the option to replace the [a-z] with 0[a-z], then sort them and replace again

sort(s:string[])
{
   return s.map(x=>x.replace(/([a-z]+)/g,'0$1'))
           .sort()
           .map(x=>x.replace(/0([a-z]+)/g,'$1'))
}

Having the same digits means that variations such as 2.1.3 and 2.10.3 are not allowed, but 2.01.3 and 2.10.3 are acceptable

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

Avoiding the Popover Component from Covering the Screen When the Menu Component Opens in React Material UI

I have implemented a Menu component to display a menu upon hovering over an element. However, I have encountered an issue where the menu includes a Popover component that opens up and covers the entire screen as an overlay, preventing interaction with th ...

Customize cursor using CSS

I have a div with overflow: hidden that I am making scrollable by allowing the user to click and drag the background. There are links and buttons within this space. Here is the CSS I am using for this: #div-grabscroll { cursor: url(../img/op ...

Manufacturing TypeScript classes that are returned by a factory

Developed a custom library that generates classes based on input data and integrates them into a main class. To enhance code maintainability and readability, the logic for generating classes has been extracted into a separate file that exports a factory f ...

Tips for sending a post request using Angular 4

I'm currently facing an issue while attempting to execute a post request using Angular 4 to transmit lat and lng parameters: let data = {lat: this.newLat, lng: this.newLng}; this.http.post(url, data) .map(response => response.json()) .subscri ...

Mastering the art of filtering arrays in RxJS 6 using Observables and async functions

I am currently working with an Observable that returns data and is being bound asynchronously in HTML. Here is where I make the service call: this.ProductOptions = this.ProductService.fetchProduct(); The HTML binding looks like this: Productoptions | a ...

Adjusting diagram size based on screen width using Bootstrap and jQuery

I recently created a diagram that adjusts its size according to the screen width. However, when I implemented this code on my page, I encountered an issue where the final circle or glyph would drop to the next line instead of staying on the same line as in ...

Send in unaltered input information

Recently, I encountered an issue with a software feature that allows users to partially edit their existing information. It seems that only the edited part gets submitted correctly, while the unedited sections end up empty. I suspect the problem arises fro ...

Steps to turn off fancybox for mobile and show the full image instead

In this scenario... I am seeking a way to deactivate fancybox functionality on mobile devices. I have already discovered one method to disable it... And now I want to directly show the large image in the a href="xxx_large.jpg" instead of using the img src= ...

The modal remains closed: Error - Attempting to access property 'open' of undefined

I've been attempting to showcase a pop-up that I implemented as a modal, but I keep getting this error: TypeError: Cannot read property 'open' of undefined The pop-up was created as a component: import { Component, OnInit, ViewChild, Ele ...

What is the maximum number of users that my Laravel app can accommodate when integrated with Pusher?

My app currently has between 300 and 900 subscribers, and I am looking to add real-time product information using pusher.com. While the implementation was straightforward, I found the pricing confusing. The startup plan costs $49 per month and allows for ...

Is it possible to use the same identifier for both the name and id attributes in HTML?

In the world of coding, the "name" attribute is often used in server-side programming to send name/value pairs in requests. On the other hand, the "id" attribute is commonly utilized in client-side programming such as Javascript and CSS. However, both att ...

Leveraging TipTap.dev for building a joint editing platform -

I have integrated the collaboration feature from tiptap.dev into my NextJS application. Initially, I used their CLI command for the Hocuspocus server which worked well on port 1234 locally and synchronized text editing across browsers seamlessly. However, ...

Learn how to use jQuery to load a text file containing arrays and then format them as

I'm attempting to load a .txt file containing multidimensional arrays using AJAX, and then sort through the data to display it on my website. However, I'm facing an issue where the data is only returning as plain text, even after trying to use JS ...

Please ensure all three of the last checkboxes are ticked before finalizing submission

Here is the list of checkboxes for my PHP form. I am trying to figure out how to write a script that will only allow the form to be submitted if the last three checkboxes are checked. I have tried looking at similar questions but haven't found the sol ...

What steps should I take to fix the Typescript error showing up in my Next.js route?

import type { NextApiRequest, NextApiResponse } from "next"; import db from "../../app/libs/dbConn"; interface DataProps { auth: [ { name?: string; email?: string; passwordHash?: string; } ]; status: n ...

The constructor for audio in Next JS cannot be found

I'm facing an issue and struggling to find a solution. My project follows the standard structure of Next JS. In the root directory, I have included a components folder. Within the components folder, there is a component with the following code: imp ...

Error message: Unable to retrieve `__WEBPACK_DEFAULT_EXPORT__` before initializing Firebase Admin in a nx and nextjs application

My current project involves a Typescript Nx + Next.js App integrated with Firebase (including Firebase Admin). In this codebase, I have defined a firebase admin util as shown below - // File ./utils/FirebaseAdmin.ts // import checkConfig from './check ...

jqgrid now features inline editing, which allows for the posting of only the data that

My jqGrid includes editable columns, and I am looking for a way to only post the data of columns where changes have been made. Here is an example of my colModel: colModel: [{ name: 'I_PK', index: 'u.I_PK ...

Problem with Next.js router language settings

I have configured different locales for our application including uk and us. For the blog section, we can use either us/blog or just /blog for the uk locale. After switching to the us locale like this: (locale = "us") const updateRoute = (locale ...

What are the steps to showcase a randomly generated number in a live Flot chart using Json?

In my C# page, I have created a random number stored in a json object: if (method == "rnd") { //Random number this.Page.Response.ContentType = "application/json2"; Random rnd = new Random(); int nr = rnd.Next(1, 100); // generates a number ...