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
2

6 Answers 6

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.

2
  • This solution will work only when string having the same prefix/suffix. In other cases it won't work
    – Sampath G
    Commented Jan 6, 2018 at 5:11
  • @SampathKumarG, the pattern of the the input string clearly indicates that the number appears only at the end.
    – Mamun
    Commented Jan 6, 2018 at 5: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

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);
2
  • By OP: "And Prefix may not be sample all the time" Commented Jan 6, 2018 at 5:30
  • I have substring the string. Commented Jan 6, 2018 at 5:32
0

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

0
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['sample1', 'sample12', 'sample3'];
myArray.sort(collator.compare);

Try this out.

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)

1
  • Here the case var array = ['sample0','sample1','sample11','sample10','sample13', 'sample14','sample2','sample21','sample3'] will not fail. Note "sample10" in array Commented Jan 6, 2018 at 4:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.