Sort the array in alphabetical and numerical order while meeting a specific condition

In my code, I am attempting to sort an array based on two conditions. Specifically, I need to ensure that Pos 10 comes after single digits and follows a specific order after that.

Initially, I tried to prioritize strings containing the word first, but when sorting alphabetically, it resets A to the top. How can I achieve the desired outcome?

const arr = [
  'Pos 10 second',
  'Pos 10 A third',
  'Pos 10 first',
  'Pos 1 second',
  'Pos 1 A third',
  'Pos 1 first',
  'Pos 2 second',
  'Pos 2 A third',
  'Pos 2 first',
]

const res = arr
  .sort((a, b) => {
    if (a.includes('first')) {
      return -1
    } else {
      return 1
    }    
  })
  .sort((a, b) => a.localeCompare(b, 'en', { numeric: true }))

console.log(res)

/* Expected output
[
  'Pos 1 first',
  'Pos 1 second',
  'Pos 1 A third',
  'Pos 2 first',
  'Pos 2 second',
  'Pos 2 A third',
  'Pos 10 first',
  'Pos 10 second',
  'Pos 10 A third'
] */

Answer №1

To organize the second set, utilize the match function on numbers found within the string input, which should be converted to the data type Number.

const organizedList = [
    'Pos 10 second',
    'Pos 10 A third',
    'Pos 10 first',
    'Pos 1 second',
    'Pos 1 A third',
    'Pos 1 first',
    'Pos 2 second',
    'Pos 2 A third',
    'Pos 2 first',
  ]
  .sort((a, b) => a.includes(`first`) ? -1 : 1)
  .sort((a, b) => +a.match(/\d+/) - +b.match(/\d+/));
document.querySelector(`pre`).textContent = 
  JSON.stringify(organizedList, null, 2);
<pre></pre>

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

execute the command only if all ava tests succeed

I'm working on creating an npm script that will execute Ava, and if it is successful, will then run another deploy command. Is there a way to obtain the result of an Ava test in JavaScript, or to save it to a file or pass it to a subsequent command? ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

VueJS Error: Unable to access the 'className' property of an undefined variable

I'm currently working on a menu design project where I need to highlight the active tab/page that the user is on by adding a color class and utilizing JavaScript to update the active link. Here's a snippet of my template: <div class="menu ...

Created a notification for when the user clicks the back button, but now looking to remove it upon form submission

My survey is lengthy and I don't want users to accidentally lose their data by clicking the back button. Currently, I have an alert that warns them about potential data loss, but the alert also pops up when they submit the form. Is there a way to disa ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

Implementing conditional statements using jQuery for multiple selections

Having two unique IDs, I am planning to set a condition that corresponds with my query. $("#foo", "#bar").foo.bar({ baz: function() { if(selector == "#foo") { console.log("foo"); } else { console.log("bar"); } } }); ...

The onload function for a JSP embedded in an IFrame was causing the IFrame to expand and fill the entire browser

I am encountering an issue with an IFrame inside a DIV where the SRC attribute is being dynamically set by a JavaScript function. When the SRC is set to "file.jsp", an onload function within the file.jsp containing style adjustments was causing the IFrame ...

Tips for accessing every "results" (parameters) from an API

Here is the response I received after making an API call in my attempt to retrieve each "bloc" result using a .forEach. const app = express(); const axios = require('axios') jobList = []; app.get('/getAPIResponse', function(req, res) ...

How can I remove a dynamically added <tr> element using jQuery?

I insert the <tr> into the <tbody> for (var i = 0 ;i < 12 ;i++){ $(`<tr><td>test</td></tr>`).appendTo('#songsTbody'); } within this HTML structure. <tbody id="songsTbody"> </tbody> ...

Apparent malfunctions in Bower packages

Here are some of the packages available on bower: bootstrap-ui, angular-ui-bootstrap, and angular-ui-bootstrap-bower. It appears that only angular-ui-bootstrap-bower has built js files. Can anyone provide more information on this? ...

Position the label and the select dropdown side by side within the sweetalert 2 component

Can anyone provide an example of aligning a label and dropdown in the same row using sweetalert2? I attempted to customize the label placement, but it appears on a separate line. I would like to log the selected dropdown item upon clicking the OK button. ...

Utilizing HTML and jQuery to load a dynamic URL within a div placeholder

I'm experiencing some difficulty with loading a custom URL. Essentially, the user will click on a series of navigation links that will dynamically load the relevant content in a tabbed bootstrap jumbotron. The navigation links vary based on data store ...

Loading a local CSS file upon opening a tab with a specific URL

When opening a tab to load a local HTML file from an addon (using addon-sdk), the following code is used: tabs.open({ url: self.data.url('index.html'), onReady: myScript }); However, there seems to be no straightforward way to include a CSS ...

Issue with Slick Grid not updating after Ajax request

I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...

What is holding Firestore back from advancing while Firebase Realtime Database continues to evolve?

I am currently working on a chat application using Firebase within my Vue.js project. In this setup, I need to display the user's status as either active or inactive. To achieve this, I implemented the solution provided by Firebase at https://firebase ...

Exploring jQuery.each: A guide to navigating JSON objects

As a beginner in working with JSON, I am struggling to iterate over a JSON response received via AJAX. My objective is to extract and loop through checkbox values retrieved from a database table such as 2,3,7,9,3. However, I am currently facing difficultie ...

Issue with Bootstrap Carousel: all elements displayed at once

I'm in the process of building a carousel. I have set up the structure, but I only want five blocks to be visible initially, with the sixth block appearing after clicking an arrow. How can I achieve this? My strategy: (adopted from here) img{ b ...

Error with JSON parsing in JavaScript when processing large numbers

After requesting a list of approved tweets from a webserver in JSON format, I visited the URL: http://localhost:8000/showtweets/?after_id=354210796420608003 and received the following JSON response: [{ "date": "2013-07-08T12:10:09", "text": "#R ...

Utilizing JavaScript/jQuery to activate a Bootstrap navbar post-page load

Having trouble triggering Bootstrap's navbar with plain JavaScript/jQuery while using Bootstrap 3.3.6 and jQuery 1.11.3. The data structure provided for my application cannot be modified in terms of adding classes or ids. <ul> <li ...