First organizing text before numerals on alphanumeric strings

My array looks like this

["1","0K","11",1,"KE","PQ",5,"5"]

I need to sort it first by text and then by number as shown below

["KE","PQ","0K","1",1,5,"5","11"]

I attempted using the local compare method but it was not effective.

function desc(a,b){
  //the code below needs improvements
  return b.toString().localeCompare(a, undefined, {
    numeric: true,
    sensitivity: "base",
  });
}

function sort(order) {
  return order === "desc"
    ? (a, b) => desc(a, b)
    : (a, b) => -desc(a, b);
}

function stableSort(array, cmp){
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    const order = cmp(a[0], b[0]);
    if (order !== 0) return order;
    return (a[1]) - (b[1]);
  });
  return stabilizedThis.map((el) => el[0]);
}

var arr = ["1","0K","11",1,"KE","PQ",5,"5"];
console.log(stableSort(arr, sort("asc")))

Answer №1

To organize the data effectively, consider implementing `filter` functions to extract strings containing numbers and separate them from other entries. By doing this, you can distinguish between numbers and strings within the dataset, enabling you to sort them according to your preferences accordingly.

const data = ["1","0K","11",1,"KE","PQ",5,"5"];

const stringsWithNumbers = data.filter(x => /\d+[a-zA-Z]/.test(x));

const rest = data.filter(x => !stringsWithNumbers.includes(x));

const numbers = rest.filter((x) => parseInt(x, 10));
const words = rest.filter((x) => !parseInt(x, 10));

const result = [
...words.sort((a, b) => a.localeCompare(b)), 
...stringsWithNumbers.concat(numbers).sort((a, b) => parseInt(a) - parseInt(b)),
];

console.log(result);

Answer №2

function customSort(arr = []) {
  const nonAlpha = /[^a-zA-Z]/g, nonNum = /[^0-9]/g;
  return arr.sort((a, b) => {
    const aStr = String(a), bStr = String(b);
    const aAlpha = aStr.replace(nonAlpha, ""), bAlpha = bStr.replace(nonAlpha, "");
    const alphaCompare = bAlpha.localeCompare(aAlpha);
    if(alphaCompare) return alphaCompare;
    const aNum = +aStr.replace(nonNum, ""), bNum = +bStr.replace(nonNum, "");
    return aNum - bNum;
  });
}

console.log( customSort(["1","0K","11",1,"KE","PQ",5,"5"]) );

Answer №3


        const items = ['apple', 'banana', 5, 'cherry', 3, 'pear'];

        const wordItems = [];
        const numItems = [];

        items.forEach((item) => {
            if(Number(item)){
                numItems.push(item);
            } else {
                wordItems.push(item);
            }
        });

        wordItems.sort();
        numItems.sort((a, b) => a - b);

        const sortedItems = wordItems.concat(numItems);
        
        console.log(sortedItems);
    

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

Merge sorting a linked list from the bottom up

When implementing bottom-up merge sort in C language, there are various approaches to consider. The method I have chosen involves inserting single lists into a queue, dequeuing the first two lists and merging them, then enqueuing the merged lists until the ...

Each block in Svelte includes a unique shorthand attribute

I have a JSON variable that holds attributes in a specific structure: // This json variable defines the attributes for elements to be created let myElements = [ { attr1: "myAttr1", attr2: "myAttr2", }, { ...

Exploring the application of Redux in various contexts

Apologies for the vague question, but I'm a bit confused. I've recently started learning redux and now I need to integrate it into a fully-functioning project: https://github.com/CodeNinja1395/Test-task-for-inCode. There is a branch for the redux ...

What steps should I take when dealing with two dynamic variables in a mediator script within the WSO2 ESB?

I'm facing an issue with my if condition - it doesn't work properly when the value is static. However, when I make `annee2` and `annee1` static (for example =2019), it works fine. Here's the code snippet: <script language="js"&g ...

JavaScript can be used to enable or disable a text box within a GridView when a checkbox is changed

I have a GridView on a webpage containing a Textbox and a CheckBox. I want the Textbox to be enabled when the CheckBox is checked, and disabled when it is unchecked using pure javascript. Can anyone help me solve this issue? Thank you in advance. <asp ...

When attempting to create a table in Swift, I noticed that the array appears to be empty

After printing the 2 arrays in the get data function, I noticed that they contain the values I need. However, when I try to populate a tableview with these arrays, the count is zero and both arrays are empty. I've spent hours trying to troubleshoot th ...

Vuetify recognizes the data; however, it is not being displayed/rendered

I have a project that utilizes Vuetify and I need to display a table of "customer" information. Everything was functioning properly with Vuetify 1.5, but now I am required to upgrade to the latest version, which is 2.0. The issue I'm encountering is ...

How can NgRx be used to properly reset or empty an array within the state object?

What is the proper way to reset an array in an NgRx reducer? I am using NgRx to create a basic reducer that includes an empty array called myArray in the initial state: import * as MyActions from './my.actions'; const myState = { myValue: & ...

Implementation of Undo/Redo feature in an AngularJS CRUD application

We are exploring the idea of developing an AngularJS application similar to Excel that includes support for undo/redo functionality when editing cells. Do you have any suggestions on the most effective approach to implement this feature? I am not only in ...

Tips for successfully passing dynamic values into toLocaleTimeString

Is there a way to pass a dynamic value into the toLocaleTimeString function? The format of the time will vary depending on the user's location. For instance, a user in the UK might see 18:00:00, while someone in America would see 6:00:00 PM. The main ...

Screen readers are unable to "read" text that is identified through aria-describedby

When enhancing my web application for accessibility, I encountered a challenge. I have implemented two required fields in a form that should display separate error messages as spans. To accomplish this, I am utilizing aria-invalid to signal when the fields ...

JavaScriptExecutor Returns a Null Value

I'm having trouble running the code below in selenium javascript executor when passed as a string. It works perfectly fine on console. Can someone please help me with this issue? I've even tried wrapping the entire script into a function, but th ...

What is the most efficient way to add or remove Date objects from arrays?

Struggling to update a calendar using the Datepicker component with Vue.js, I encountered some issues with adding and deleting items (specifically Date objects) I have written two javascript functions: one for adding new Dates to an array, and another for ...

How to display an Array using PHP

I'm pretty new to using PHP. Currently, I'm working on recreating a page where customers can order pizza. However, I'm facing an issue with displaying multiple options selected from a dropdown menu. Instead of showing all the choices selecte ...

Utilizing PHP and Ajax to Transfer Selected Option into Input Field

I need a solution to automatically transfer the selected value/option from a drop down menu into an input field without any page refresh. Ideally, I would like this functionality to work seamlessly without requiring an extra button click, so that the val ...

My goal is to create a JavaScript application that functions as a basic counting tool

I've encountered an issue with my simple counter code - it's not functioning properly. The goal is for the decrement function to stop running when the count reaches 0. I'd appreciate any help in troubleshooting what might be wrong. let count ...

Error: The import statement is invalid when used outside of a module

Click here to watch the video <!DOCTYPE html> <html> <head> <title>Three.js</title> <style type="text/css> html, body {margin: 0; padding: 0; overflow: hidden} </style> </head> <body> <div id="w ...

How can we ensure that the entire BS4 Navbar (on smaller screens) is clickable, allowing users to show/hide the submenu by touching anywhere within the area?

https://i.sstatic.net/03po7.png My goal is to make the entire navbar area touchable, rather than just having a button. I believe this can be achieved by adjusting the default Bootstrap 4 navbar settings: HTML: <nav id="menu-navbar" class="navbar navb ...

Problem encountered with Firefox when using jQuery's hide() function

I am facing an issue with the hide() function in a project I am working on. The selected div layer is not hiding as expected. Everything seems to be functioning correctly in Safari and Chrome, but unfortunately, it is not working in Firefox :-( You can v ...

Challenge with querying the database logic

I'm working with a database and extracting specific fields: BookDate -- AirlineCode -- BkngVal My goal is to save the output in a json file in this structure: [{ Date: 2016-01-03, Airline Code: BA, Airline BkngVal: 1234.00, Airline Code: VS, Airlin ...