Organizing an array in JavaScript that includes both version numbers and letters, with each letter representing a specific numerical value

If given an array similar to this one:

input = [
    "1.1",
    "1.c",
    "1.b",
    "1",
    "D",
    "b",
    "4",
    "2.1.2",
    "5.1",
    "3",
    "2.a.1"
]

What is the best approach to sorting it in order to achieve the following result:

sorted = [
    "1",
    "1.1",
    "1.b",
    "1.c",
    "b",
    "2.a.1",
    "2.1.2",
    "3",
    "4",
    "D",
    "5.1"
]

In the sorting process, consider:

'a' or 'A' should be treated as 1,

'b' or 'B' should be treated as 2,

and so forth.

The array only contains numbers and letters, no symbols.

I have attempted the following code:

input = ["1", "1.1", "1.b", "1.c", "b", "2.a.1", "2.1.2", "3", "4", "D", "5.1"]
console.log(input.sort((a, b) => a.localeCompare(b)));

This code did not produce the desired outcome. I would appreciate any suggestions or assistance with this issue. Thank you!

Answer №1

If you want to arrange the inputs in a specific order, you can achieve this by utilizing a custom function along with the sort function. Below is an example of how I tackled this task:

input = [
    "1.1",
    "1.c",
    "1.b",
    "1",
    "D",
    "b",
    "4",
    "2.1.2",
    "5.1",
    "3",
    "2.a.1"
]

function convert(el){
 const nums = el.split(".");
 return nums.map(n => {
    if(n.match(/[A-z]/)){ 
      return n.toLowerCase().charCodeAt(0) - 96;
    }
    return n;
  }).join(".");
}

input.sort((a,b) => {
  const convA = convert(a);
  const convB = convert(b);
  return convA.localeCompare(convB);
})

console.log(input);

Answer №2

Check out a simplified version of @mgm793's sorting function:

input = [
    "1.1",
    "1.c",
    "1.b",
    "1",
    "D",
    "b",
    "4",
    "2.1.2",
    "5.1",
    "3",
    "2.a.1"
]

function convertStr(str){
 return str.toLowerCase().replace(/[a-z]/g, char => char.charCodeAt(0) - 96)
}

input.sort((a, b) => convertStr(a).localeCompare(convertStr(b)))

console.log(input);

Here is an enhanced version that maintains stability for numbers up to 26 and letters up to z:

input = [
    "1.10",
    "1.m",
    "1.b",
    "1.1.3",
    "1",
    "F",
    "b",
    "4",
    "2.1.2",
    "5.1",
    "3",
    "2.a.1"
]

let result = input.map(e => [e.toLowerCase().replace(/\d+/g, num => String.fromCharCode(+num + 96)), e])
             .sort(([a], [b]) => a.localeCompare(b))
             .map(([_, e]) => e);

console.log(result);

This code snippet converts numeric values and alpha-numeric combinations into strings using characters between a and z, along with dots (.). These transformed strings are easily sorted using the String.localeCompare() method. The original values are paired with these modified strings in a temporary array, which is then sorted based on the string comparison results. Finally, the original values are extracted from this temp array in a final mapping loop. This approach ensures that the original input array remains unchanged while the variable result holds the sorted values.

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

Using VueJS to dynamically load a separate component into a Vue instance

Currently, I am working on revamping our web platform at my job. This includes migrating a significant amount of outdated JavaScript/jQuery code to VueJS. We have a "global.js" file that contains our Vue components and a "vendor.js" file that includes Vue ...

401 Access Denied - Browser extension utilizing Angular JS

In my attempt to implement login functionality within a Chrome extension using Angular, I am consistently encountering a 401 UNAUTHORIZED error. Below is the code snippet I am using: angular.module('chrome-extension') .controller('LoginCont ...

What is the best way to link this information to access the data attribute?

Currently, I am looking to streamline the data retrieved from firebase so that it can be easily displayed in a FlatList component. How can I transform my data into a simple array that can be iterated over in the FlatList? UPDATE! I have multiple other coi ...

Images copied using Gulp are often distorted or incomplete

There is a simple task of moving an image from one folder to another. gulp.task('default', function () { return gulp.src('./img/*.*') .pipe(gulp.dest('./image')); }); Previously, everything was running smoothly, b ...

Convert the Date FR and Date US formats to ISO date format

There is a function in my code that accepts dates in different formats. It can handle two formats: 2022-06-04 or 04/06/2022 I want all dates to be in the format: 2022-06-04 For instance: public getMaxduration(data: object[]): number { data.forEach((l ...

In JavaScript, capture data returned from a function in a separate variable using a POST REST API call

So, here's the deal - I've got this awesome code that does a POST to an API in order to fetch some data. The best part? It works like a charm when it's wrapped up neatly in a function. But now, the tricky part comes in. I need to actually re ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

Transfer an URL parameter from the URL to the server using PHP or JavaScript

My goal here is to pass the URL as a parameter named "web_url". The code snippet above shows an AJAX request being sent to a PHP server on the backend. On the PHP side, I'm attempting to capture this parameter using: $web_url = $_GET["web_url"]; H ...

Posting data using an Ajax form submission without the need for page

After numerous attempts, I am still facing an issue where clicking the Submit button causes the page to refresh. What changes should I make to resolve this problem? <script> $('#submit').on('submit', function(event) { event.pre ...

Ensuring a fixed table with vertical scrolling only, no horizontal scrolling, while scrolling in either direction

I'm working with an HTML fixed design that contains a center-aligned table with extensive data scrollable both vertically and horizontally. To address the issue of keeping column headers visible when scrolling vertically, I used jQuery's clone() ...

Ways to locate two div class elements that are generated dynamically

I am looking to dynamically create 2 divs in different locations. One for displaying information and another for editing information. I want to be able to delete both divs with the same class when using the delete button. Since they are located in differe ...

Unexpected token N error was thrown while using the Jquery .ajax() function

While working on a form submission feature using JQuery .ajax() to save data into a MySQL database, I encountered an error message that says "SyntaxError: Unexpected token N". Can someone please explain what this means and provide guidance on how to fix it ...

What is the best way to transfer global Meteor variables to templates and effectively utilize them?

I am in the process of developing a compact, single-page application game that emulates the dynamics of the stock market. The price and behavior variables are influenced by various factors; however, at its core, there exists a finite set of universal varia ...

Removing HTML DOM elements from a string using JavaScript: A step-by-step guide

Hey there, I'm currently working on my angular application. When it comes to inserting the first 100 characters of content into the "description" meta tag for Facebook sharing, I've run into an issue. The description ends up including the HTML el ...

Using React Native with TypeScript to Select the Parent and Child Checkboxes within a FlatList

My objective is to ensure that when a user selects a checkbox for one of the parent items ('Non Veg Biryanis', 'Pizzas', 'Drinks', 'Desserts') in the flatlist, all corresponding child items should also be selected au ...

Several mistakes occurred involving auth0, react, apollo, babel, and webpack

I seem to be facing some challenges while trying to integrate auth0 into my project. Every time I fix one issue, another one pops up and it's always the same trio of errors: -require is not a function -window is not defined -missing class properties ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Creating a Social Media Platform with JavaScript, Bootstrap, JQuery, PHP, and Mysqil

I am currently in the process of developing a social networking platform that will have similar features as Instagram. Users will be able to log in, create posts, leave comments, like content, share posts, and send data to a server for storage or display p ...

Utilizing multiple instances of fs.writeFile in Node.js

I am currently managing a hotel's check-in/out information on an http server in Node.js. I store all the JSON data in memory and write it to a file using "fs.writeFile". Typically, the data does not exceed 145kB, but when consecutive calls to fs.write ...