What is the best way to arrange an array based on two properties using regular expressions?

Below is an array containing items:

var myArray =
 [
 {catNum : 'CAT I #4', trackingNumber : 'ORG Cat-123'},
 {catNum : 'CAT I #6', trackingNumber : 'ORG Dog-345'},
 {catNum : 'CAT I #2', trackingNumber : 'ORG Cat-123'},
 {catNum : 'CAT I #2', trackingNumber : 'ORG Cat-345'},
 {catNum : 'CAT II #15', trackingNumber : 'ORG Fish-264'},
 {catNum : 'CAT III #1', trackingNumber : 'ORG Bird-123'},
 {catNum : 'CAT II #7', trackingNumber : 'ORG Dog-533'},
 ]

The goal is to sort the array first by catNum, and then by the tracking number in case of identical catNums.

Initially, sorting was accomplished for catNum property using the code below:

myArray.sort(function mySort(a, b)
                {
                    return catTrackSort(a, b);
                });

 function catTrackSort(a, b)
        {
            var left = a.catNum.match(/CAT ([IV]+) #([0-9]+)/);
            var right = b.catNum.match(/CAT ([IV]+) #([0-9]+)/);

            if (left[1].length === right[1].length)
            {
                return left[2] - right[2];
            }
            else
            {
                return left[1].length - right[1].length;
            }
        }

To further refine the sorting process based on alphabetical order of the trackingNumber when catNum values are the same, the following attempt was made:

function catTrackSort(a, b)
        {
            var left = a.catNum.match(/CAT ([IV]+) #([0-9]+)/);
            var right = b.catNum.match(/CAT ([IV]+) #([0-9]+)/);

            if (left[1].length === right[1].length)
            {
                if (left[2] === right[2])   
                {
                    var left1 = a.trackingNumber.match(/ORG ([A-Z]+)/);
                    var right2 = b.trackingNumber.match(/ORG ([A-Z]+)/);

                    return left1[1] - right1[1];
                }

                else return left[2] - right[2];
            }
            else
            {
                return left[1].length - right[1].length;
            }
        }

If you have any suggestions or corrections on how to achieve the desired sorting, please share them.

Answer №1

To achieve sorting with map, you can refer to the Sorting with map guide and create a new array based on the sort parameter.

mapped.sort(function (a, b) {
    return a.cn[0] - b.cn[0] || a.cn[1] - b.cn[1] || a.tn[0].localeCompare(b.tn[0]) || a.tn[1] - b.tn[1];
    //        roman number         arabic number              organisation               number of org     
});

var myArray = [{ catNum: 'CAT I #4', trackingNumber: 'ORG Cat-123' }, { catNum: 'CAT I #6', trackingNumber: 'ORG Dog-345' }, { catNum: 'CAT I #2', trackingNumber: 'ORG Cat-123' }, { catNum: 'CAT I #2', trackingNumber: 'ORG Cat-345' }, { catNum: 'CAT II #15', trackingNumber: 'ORG Fish-264' }, { catNum: 'CAT III #1', trackingNumber: 'ORG Bird-123' }, { catNum: 'CAT II #7', trackingNumber: 'ORG Dog-533' }],
    mapped = myArray.map(function (a, i) {
        var cn = a.catNum.match(/CAT ([IV]+) #([0-9]+)/),
            tn = a.trackingNumber.match(/ORG ([A-Z]+)-([0-9]+)/i);
        cn.shift();
        cn[0] = { I: 1, II: 2, III: 3, IV: 4, V: 5, VI: 6, VII: 7, VIII: 8 }[cn[0]];
        tn.shift();
        return { index: i, cn: cn, tn: tn };
    }),
    result;

mapped.sort(function (a, b) {
    return a.cn[0] - b.cn[0] || a.cn[1] - b.cn[1] || a.tn[0].localeCompare(b.tn[0]) || a.tn[1] - b.tn[1];
});

result = mapped.map(function (el) {
    return myArray[el.index];
});

console.log(result);

Answer №2

How do you feel about this?

function sortCatTrack(a, b)
{
    if (a.catNum == b.catNum) {
        // if tracking numbers are also the same, return 0 to maintain order
        if (a.trackingNumber == b.trackingNumber) {
            return 0;
        }

        // sort the tracking numbers alphabetically
        var testABC = [a.trackingNumber, b.trackingNumber]
        testABC.sort() // default behavior is alphabetical sorting

        // check if the test array changed order
        if (testABC[0] == a.trackingNumber) {
            return -1;
        }
        else {
            return 1;
        }
    }
    else {
        // logic to sort by catNum goes here
    }
}

Appears to be functioning well in my fiddle.

Answer №3

Although my JavaScript skills are lacking, I can provide a C# example for those who are interested in a different approach.

// Generating sample data
var values = new List<Tuple<int, int>>();
var rnd = new Random((int)DateTime.Now.Ticks);

for(int i = 0; i < 100; i++)
{
    values.Add(new Tuple<int, int>(rnd.Next(10), rnd.Next(10)));
}

// Grouping by the first item in the tuple
var groupedValues = values.GroupBy(x => x.Item1).OrderBy(grp => grp.Key).ToList();

List<Tuple<int, int>> sortedValues = new List<Tuple<int, int>>();

// Ordering by the second item in the tuple within each group
groupedValues.ForEach(grp => sortedValues.AddRange(grp.OrderBy(x => x.Item2)));

sortedValues.ForEach(sv => Console.WriteLine($"{sv.Item1} {sv.Item2}"));

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

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

I am seeking guidance on extracting specific data from a JSON file and presenting it in an HTML table using jQuery

I am currently working on extracting specific elements from a JSON file and displaying them in an HTML table. I have successfully retrieved the data from the JSON file, stored it in an array, and then dynamically created an HTML table to display the conten ...

Issue: AngularJS modal not appearing when utilizing partial for template URLExplanation: The Angular

I am having trouble with a modal in a partial file that is supposed to be loaded into my main view using an ng-include tag. However, the template cannot be found and I do not see it being loaded in the console or network tab. The error message I receive is ...

The error message "node-soap - callback is not a function" is indicating that there

Encountering a common TypeScript error while calling a SOAP method on a node-soap client in NodeJS. Seeking guidance on resolving this issue. https://www.npmjs.com/package/soap - version: 0.35.0 Sample Code Snippet const [result] = await mySoapClient.Per ...

The initial render of Next.js is not properly loading the CSS files

Encountering an issue with the initial load of the mobile app version; it seems that the CSS of my component covering the page is not loading correctly on the first screen load. However, when resizing to desktop and then switching back to mobile view, the ...

Bower downloads the identical package but arranges it in a distinct file structure

We operate a TeamCity build server that is utilizing three different buildusers all configured similarly. We have integrated an angular/grunt project using yeoman Update 6 Noted an issue with bower https://github.com/bower/bower/issues/1709 Why does bow ...

Activate a function when the v-data-table in Vuetify is expanded and then collapsed

While trying to create a v-data-table, I came across some odd behavior when monitoring the expanded.sync value. The first layer's expanded.sync value seems normal, but the second layer's expanded.sync has three consecutive identical records. I w ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

The Growth of Integer Array

Curious about how to dynamically expand an integer array in C? I recently learned about malloc, realloc, and sizeof but could use a bit more guidance on how they function. Could someone provide a simple example of how to achieve this in C? ...

Tips for using a fluent interface to apply a method to all data member variables simultaneously

I have a class structured as follows: class example{ private $foo = array(); private $bar = array(); public function getFoo(){ return $this->foo; } public function getBar(){ return $this->bar; } //fo ...

Encountering Internal Server Error when C# WebMethod communicates with JavaScript AJAX call

I've encountered an issue where my AJAX call to a C# WebMethod is not returning the expected result. Instead, it keeps showing an "Internal Server Error" message. A button triggers a JavaScript function: <button id="btn" onclick="Create();">fo ...

Increasing the nth-child Selector in Jquery

Referring to this I am looking to cycle through the nth-child selector, which involves: var i = 1; var tmp = $(this).find('td:nth-child(i+1)'); // I wonder how this can be achieved i++; I have rows with dynamically generated columns i ...

Setting up a static array of character pointers in C++

Is there a way to transform the array of pointers into a private static member of a class? class Auth { private: static char *attribs[3]; attribs[0]="uid"; attribs[1]="cn"; attribs[2]=NULL; } I'm struggling to figure out where exactl ...

Using Regular Expressions: Ensuring that a specific character is immediately followed by one or multiple digits

Check out the regular expression I created: ^[0-9\(\)\*\+\/\-\sd]*$ This regex is designed to match patterns such as: '2d6', '(3d6) + 3', and more. However, it also mistakenly matches: '3d&apos ...

What is the best way to categorize an array based on a specific key, while also compiling distinct property values into a list

Suppose there is an array containing objects of type User[]: type User = { id: string; name: string; role: string; }; There may be several users in this array with the same id but different role (for example, admin or editor). The goal is to conv ...

Error: React Select input control is throwing a TypeError related to event.target

Having trouble changing the state on change using a React Select node module package. It works with regular text input, but I can't quite get it to work with this specific component. The error message "TypeError: event.target is undefined" keeps poppi ...

How can we track and record NaN values in JavaScript/TypeScript as they occur in real-time?

Is there a reliable method to identify and prevent NaN values during runtime, throughout all areas of the application where they might arise? A) Are there effective linting tools available to alert about possible occurrences of NaN values within specific ...

Dominant Editing through ASP.Net Roles

Looking for guidance on how to effectively use knockout with asp.net membership roles in MVC 4. My goal is to incorporate an editable grid on the page based on whether the user is an administrator or a 'registered user'. I want to ensure that use ...

A TypeScript method for accessing deeply nested properties within an object

I'm currently working on a function that utilizes typings to extract values from a nested object. With the help of this post, I managed to set up the typing for two levels successfully. However, when I introduce a third (known) level between the exis ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...