Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort javascript array with word_number values

how do I sort an array

var arr = new Array("word_12", "word_59", "word_17");

so that I get

["word_12", "word_17", "word_59"]

Thanks!

like image 996
user1054134 Avatar asked Jan 20 '26 23:01

user1054134


2 Answers

you need to write a sort method (you can write any that you like) which splits the string on the _ and uses the second part as a numeric sort value.

​    function sortOnNum(a,b){
         //you'll probably want to add a test to make sure the values have a "_" in them and that the second part IS a number, and strip leading zeros, if these are possible
         return (a.split("_")[1] * 1 > b.split("_")[1] * 1)? 1:-1;// I assume the == case is irrelevant, if not, modify the method to return 0 for ==
    }

    var ar = new Array ("foo_1", "foo_19", "foo_3", "foo_1002");

ar.sort(sortOnNum); //here you pass in your sorting function and it will use the values in the array against the arguments a and b in the function above

alert(ar); // this alerts "foo_1,foo_3,foo_19,foo_1002"

Here's a fiddle: http://jsfiddle.net/eUvbx/1/

like image 165
Yevgeny Simkin Avatar answered Jan 23 '26 11:01

Yevgeny Simkin


The following assumes your number will always be at the very end of the string. Note, I've added a few additional examples into the array to demonstrate the differing formats this can work with:

var numbers = ["word_12", "word_59", "word_17", "word23", "28", "I am 29"];

numbers.sort(function(a,b){
    return a.match(/\d+$/) - b.match(/\d+$/);
});

Which results in:

["word_12", "word_17", "word23", "28", "I am 29", "word_59"]
like image 31
Sampson Avatar answered Jan 23 '26 11:01

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!