What is the best way to organize strings in this particular order?

Exploring File Sorting in qBittorrent, a BitTorrent Client

Note: I have no personal interest in torrents or files, and I haven't engaged in downloading any of them.

How can we achieve similar string sorting behavior in JavaScript as seen in qBittorrent? The logic seems intentional rather than random.

Initial Attempt

strings.sort((a, b) => a.localeCompare(b, "en", {
    sensitivity: "case",
    caseFirst: "upper",
    numeric: true
}));

Unexpected Outcome

[
    "1.ico",
    "01.ico",
    "03.ico",
    "04.ico",
    "05.ico",
    …
]

Answer №1

Organize by the following rules:

  • If the item begins with a number, prioritize it
  • Next, consider the length of the leading number
  • Lastly, apply a natural sorting method

const array=["1.ico","01.ico","03.ico","04.ico","05.ico","7-zip ICO m1losh_1.ico","07.ico","7z-silver.ico","7z.ico","7z1.ico","7zfm.ico","7Zip.ico","7ZSFX.ico","7zSfxCreate_99.ico","7ZSplit.ico","7zz.ico","08.ico","09.ico","11.ico","14.ico","22.ico","101.ico","107.ico","128.ico","138.ico","777.ico","7833-ZeDudeMan-WinRar_vista.ico","exe.ico","hfs.ico","hg.ico","Icon.ico","Icon1.ico","icon17.ico","inst.ico","Install-2.ico","Install-3.ico","Install-4.ico","Install-5.ico","Install-6.ico","Install-7.ico","Install-8.ico","Install-9.ico","Install-11.ico","Install-12.ico","Install-13.ico","Install-14.ico","Install-15.ico","Install-16.ico","Install-17.ico","Install-18.ico","MAINICON.ico","momitor.ico","PSA_1.ico","qfInstall.ico","Readme!!!.txt","Token_7zip-dark.ico","Token_7zip-light.ico","wusa.ico"];

array.sort((a, b) => {
    const n1 = a.match(/^\d+/)?.[0],
          n2 = b.match(/^\d+/)?.[0]

    return (n1 === null) - (n2 === null)
           || n1?.length - n2?.length
           || a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'})
})

console.log(array)

Answer №2

Revised the code snippet with inspiration from @adiga and @Chris G's solutions.[a.][C.]

const strings = ["1.ico","01.ico","03.ico","04.ico","05.ico","7-zip ICO m1losh_1.ico","07.ico","7z-silver.ico","7z.ico","7z1.ico","...continues...

strings.sort((a, b) =>
    ((a.match(/^\d+/)?.[0].length || Infinity) - (b.match(/^\d+/)?.[0].length || Infinity))
        || a.localeCompare(b, "en-u-kf-upper-kn", {sensitivity: "base"})
);

console.log(strings);

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

Guide to implementing email validation within a partial using AngularJS

I am attempting to display a message like this for my input named "txtEmail": <span ng-show="frm.txtEmail.$error.email">Email is wrong!</span> This is within a partial, with the HTML container containing a form named "frm". However, it seems ...

Tips for choosing or unselecting a row within a Table utilizing the Data Grid Mui

Is it possible to implement row selection and deselection in Mui without using the checkboxSelection prop? I am looking for a way to achieve this functionality in @mui/x-data-grid when clicking on a row. Below is the code snippet from the Table Component ...

Any suggestions for solving the issue of breaking the line at the end of a <td> within a <table> element using jQuery or JavaScript?

Here is a table format that I have: $(document).ready(function() { var enteredText = document.getElementById("textArea").value; var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length; var characterCount = enteredText.length + numberOfLineB ...

Having trouble halting the execution at specific checkpoints within an asp.net core project containing an angular 8.0 application located in a subfolder named ClientApp

Encountering difficulties stopping at breakpoints in an asp.net core project with an angular 8.0 app located in a subfolder within ClientApp. The app I need to set a breakpoint in is located at clientapp\apps\microsympan\app\src\ap ...

Easily Implement Geocoding Functionality with jQuery

Can anyone provide guidance on creating a simple map using Jquery that plots only one location defined by longitude and latitude? The current code I have is set up to plot an array of locations, but I specifically need assistance with plotting a single poi ...

Utilizing Angular2 to access NPM package (Googleapis)

I am currently developing an Angular2 application that utilizes Webpack for the build process. I want to implement a Google oauth login feature in my application, so I have added the googleapi package from npm. However, I am facing difficulties when trying ...

display the information stored within the sports attribute using React

I am attempting to display the values stored in the sports property. So, I inserted a console log within the sports property. However, an error is being thrown: Syntax error: C:/codebase/src/containers/sports.js: Unexpected token, expec ...

What is the way to instruct Mongoose to exclude a field from being saved?

Is there a way in Mongoose to instruct it to not save the age field if it's null or undefined? Or is there a method to achieve this in Express? Express router.put('/edit/:id', function(req, res) { Person.findOneAndUpdate({ _id: req.p ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Searching with parameters in the MVC framework involves utilizing specific criteria to filter data and

I am looking to create a user-friendly page where users can search for the following criteria: Search work Category Price AdType Location It is important that users are able to save their search settings in the database and easily retrieve them by copyi ...

What is the best way to retrieve the text within a select tag based on its value?

Let's say I have a value 'v' stored in a variable called 'var', and I want to display Valvo (text corresponding to the value v). Any ideas on how to achieve this? ...

The error message "TypeError XXX is not a function in NodeJS" indicates that

As I attempt to enhance the testability of my NodeJS API by incorporating a service, a peculiar issue arises. Specifically, upon injecting the service (class), an error is triggered stating that the method getTasks() does not exist. ROUTE const TodoServi ...

Tips for changing the value of a span element in an ng-repeat loop

Utilizing ng-repeat to populate my data model, I am facing an issue with displaying the first character of each contact's first and last name inside a circle shape. Below is the code snippet I am using for this purpose: HTML: <ul class="collectio ...

Ensure that one element vanishes in sync with the disappearance of another element

As part of my jQuery library development for modals, I have included a feature where the page fades when a modal is created. This effect is achieved by adding a div with a semi-transparent black overlay. Now, the challenge is to ensure that this "fade" ef ...

A React component that dynamically increases the padding CSS value to render its children components

Greetings! I am working on a scenario where a React component needs to pass a padding value to styled components while incrementing it based on the nested rendering level. For example, imagine a List component that must display a parent and child component ...

What steps should I take to make my include function operational?

As I develop a website for our entertainment company, I encounter language translation issues. Due to our diverse clientele, I implemented a multilingual feature on the site. However, during testing, all the text appeared blank. I suspect that the root of ...

By double clicking, three.js has the ability to dynamically create objects

My website features stunning 3D graphics created using three.js. There are numerous square boxes on the site, and users have the ability to add even more boxes. By double-clicking anywhere on the scene, a box will be dynamically added at that specific po ...

The response data from Axios remains undefined even after a successful request

function verifyPassword() { let pass = document.getElementById("password").value let emailAddr = document.getElementById("email").value Service.confirmLoginPassword(emailAddr, pass).then(response => { result = re ...

Load blender scene with functional lighting using THREE.JS GLTFLoader

Recently, I've been experimenting with the GLTFLoader feature in THREE.js along with the new blender exporter found here. After successfully adding a model with similar color material and importing the scene into my THREE.js project, I noticed that wh ...

Tips for enhancing the contents of a single card within a react-bootstrap accordion

Currently, I am facing an issue with my columns expanding all cards at once when utilizing react-bootstrap accordion. My goal is to have each card expand individually upon clicking on its respective link. However, I am encountering difficulties in implem ...