Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort mixed alpha/numeric array

I have a mixed array that I need to sort by alphabet and then by digit

[A1, A10, A11, A12, A2, A3, A4, B10, B2, F1, F12, F3] 

How do I sort it to be:

[A1, A2, A3, A4, A10, A11, A12, B2, B10, F1, F3, F12] 

I have tried

arr.sort(function(a,b) {return a - b}); 

but that only sorts it alphabetically. Can this be done with either straight JavaScript or jQuery?

like image 819
solefald Avatar asked Dec 02 '10 21:12

solefald


People also ask

How do you sort alpha numeric?

Alphanumeric ordering is done using the current language sort order on the client machine as defined by the operating system (i.e. Windows). The user requests the sort by clicking on the column header. A grid must have column headings in order to be sorted by the user.

How do you sort an array in numerical order?

We can use . sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or . sort((a,b)=>b-a) for descending order.

What is alphanumeric sorting example?

A list of given strings is sorted in alphanumeric order or Dictionary Order. Like for these words: Apple, Book, Aim, they will be sorted as Aim, Apple, Book. If there are some numbers, they can be placed before the alphabetic strings.

How do you sort an array alphabet?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


1 Answers

var reA = /[^a-zA-Z]/g;  var reN = /[^0-9]/g;    function sortAlphaNum(a, b) {    var aA = a.replace(reA, "");    var bA = b.replace(reA, "");    if (aA === bA) {      var aN = parseInt(a.replace(reN, ""), 10);      var bN = parseInt(b.replace(reN, ""), 10);      return aN === bN ? 0 : aN > bN ? 1 : -1;    } else {      return aA > bA ? 1 : -1;    }  }  console.log(  ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)  )
like image 113
epascarello Avatar answered Sep 19 '22 12:09

epascarello