Sort an array in specific order javascript -


i have array

arr1 = ["p2.13","p1.13","p4.13","p3.13", "p2.14","p2.14","p1.14","p4.14","p1.15","p2.15","p3.15","p4.15"]; 

how can sort array number after dot first, 13 15, sort number after "p" 1 4? finaly want array this

arr2 = ["p1.13","p2.13","p3.13","p4.13","p1.14","p2.14","p3.14","p4.14","p1.15","p2.15","p3.15","p4.15"]; 

appreciate!!

for programs include many functional programming choose underscore library. can directly call sortby function based on multiple attributes hacky trick joining them. here code:

var sortedarray = _.sortby(arr1, function(item) {     var nums = item.split('.');     return [nums[1], nums[0]].join("_"); }); 

however, can still use javascript sort function sort list customized compare function. here code:

arr1.sort(function(x, y) {   var numsx = x.split('.');   var numsy = y.split('.');   if (numsx[1] !== numsy[1]) {      return compare(numsx[1], numsy[1]);  // compare number after dot first   }   return compare(numsx[0], numsy[0]); // compare number before dot after });  // general comparison function convenience function compare(x, y) {   if (x === y) {     return 0;   }   return x > y ? 1 : -1; } 

check 2 examples on fiddle underscore sort vs javscript sort

this new account, don't have reputation post more 2 links. can search underscore library.

thanks.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -