Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the string based on numbers present in it, separated by (.)

Hi I want to sort the string based on numbers present in it e.g

  • 1.1.act2
  • 13.1.2.1.act3
  • 2.1.4.act56
  • 1.3.actorg
  • 3.1.3.args
  • 13.1.3.4.acr

I want to this in a manner

  • 1.1.act2
  • 1.3.actorg
  • 2.1.4.act56
  • 3.1.3.args
  • 13.1.2.1.act3
  • 13.1.3.4.acry

How do I achieve it in javascript?

like image 757
BaD aNgEl Avatar asked Nov 12 '22 19:11

BaD aNgEl


1 Answers

You can use the Arrays sort method with a custom iterator function. e.g:

mylist = ["1.1.act2", "13.1.2.1.act3", "2.1.4.act56", "1.3.actorg", "3.1.3.args", "13.1.3.4.acr"];

mylist.sort(function(a, b) {
    a = a.split("."); b = b.split(".");
    var parts = Math.min(a.length, b.length);
    for(var i = 0; i < parts; ++i) {
        var numA = parseInt(a[i]); var numB = parseInt(b[i]);
        if (numA != numB)
            return numA > numB;
    }
});

This is a stub and untested, but I guess you see where I'm heading

like image 62
Constantinius Avatar answered Nov 15 '22 09:11

Constantinius