1

I have array of strings

sample0
sample1
sample11
sample12
sample13
sample14
sample2
sample21
sample3

But i need in this way. I am not able to figure out the solution. And Prefix may not be sample all the time.

sample0
sample1
sample2
sample3
sample11
sample12
sample13
sample14
sample21
K Sathish
  • 247
  • 3
  • 13

6 Answers6

4

Use Regular expressions /\d+$/ to match only the number presented at the end in the string with Array's sort() like the following:

var strArr = ['sample0', 'sample1', 'sample11', 'sample12', 'sample13', 'sample14', 'sample2', 'sample21', 'sample3'];

var strRes = strArr.sort(function(a, b){
  return a.match(/\d+$/) - b.match(/\d+$/);
})
console.log(strRes);

Note: This will extract number only from the end and will sort according to that.

Mamun
  • 66,969
  • 9
  • 47
  • 59
  • This solution will work only when string having the same prefix/suffix. In other cases it won't work – Sam G Jan 06 '18 at 05:11
  • @SampathKumarG, the pattern of the the input string clearly indicates that the number appears only at the end. – Mamun Jan 06 '18 at 05:15
1

Solution-1:

var arr = ['sample0', 'sample1', 'sample11', 'sample12', 'sample13', 'sample14', 'sample2', 'sample21', 'sample3']
arr.sort(function (a, b) {
    return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});
console.log(arr);

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Solution-2:

function naturalCompare(a, b) {
    var ax = [], bx = [];
    a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
    b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });

    while(ax.length && bx.length) {
        var an = ax.shift();
        var bn = bx.shift();
        var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
        if(nn) return nn;
    }
    return ax.length - bx.length;
}

arr.sort(naturalCompare);
console.log(arr);

This solution has taken from https://stackoverflow.com/a/15479354/3910232

Sam G
  • 1,242
  • 15
  • 12
1

If the prefix "sample" is constant then

   var numString=['sample1','sample12','sample123','sample2','sample0','sample23'];

    var num=new Array(numString.length); 
    for (var i = 0; i < numString.length; i++) {
    num[i]=numString[i].substring(6);
    }
    var st=numString[0].substring(0,6);
    num.sort();
    var ne=(st + num.join(';' + st)).split(';');
    alert(ne);
MADHUR GUPTA
  • 1,014
  • 10
  • 14
0

The smart-sort package can accomplish this. I'm sure there are other solutions. Look for the keywords "natural sorting" and "smart sorting".

Daniel Centore
  • 3,220
  • 1
  • 18
  • 39
0
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['sample1', 'sample12', 'sample3'];
myArray.sort(collator.compare);

Try this out.

Pratik
  • 1,351
  • 1
  • 20
  • 37
0

var array = ['sample0','sample1','sample11','sample12','sample13',
'sample14','sample2','sample21','sample3']            
         
            var sortedArray = array.sort(function(a, b){ 
                var regXStr =  /[^a-zA-Z]/g, regXNum = /[^0-9]/g;
                var aStr = a.replace(regXStr, "").toLowerCase();
                var bStr = b.replace(regXStr, "").toLowerCase();
                if(aStr === bStr) {
                    var aNum = parseInt(a.replace(regXNum, ""), 10);
                    var bNum = parseInt(b.replace(regXNum, ""), 10);
                    return aNum === bNum ? 0 : aNum > bNum ? 1 : -1;
                } else {
                    return aStr > bStr ? 1 : -1;
                }                    
            });  
            console.log(sortedArray)
ganesh phirke
  • 471
  • 1
  • 3
  • 12
  • Here the case var array = ['sample0','sample1','sample11','sample10','sample13', 'sample14','sample2','sample21','sample3'] will not fail. Note "sample10" in array – ganesh phirke Jan 06 '18 at 04:58