简体   繁体   中英

how do I sort a array of text by the last numberic character in javascript

I have a array of texts, such as this [building2, building1 , building3, building5, building4] .

How do I sort this array by the last numeric character, so the sorted out array will be building1, building2, building3, building4, building5, building6 ?

var array = ["building200", "building10", "building3", "building5", "building4"];

array.sort(function(a, b){
  var char1 = a.substr(a.search(/\d+$/));  // get the last numbers
  var char2 = b.substr(b.search(/\d+$/));   // get the last numbers
  return parseInt(char1) - parseInt(char2); // sort by parsing to number
});

alert(array); // ["building3", "building4", "building5", "building10", "building200"]

a.search(/\\d/) will return index of first digit encountered, and a.substr(that_index) will cut string from there till the end.

Will also work if array has strings of uneven length like ["buildingsss2", "buildisng1", "building3", "building5", "builsding4"]

Hope that helps!

You can use the regular expression \\d+ to get all the consecutive numbers and then compare the two elements by substracting one from the other, like this

var data = [ 'building2', 'building10', 'building3', 'building5', 'building4' ];

data.sort(function(first, second) {
    return /\d+/.exec(first)[0] - /\d+/.exec(second)[0];
});

console.log(data);

Output

[ 'building2', 'building3', 'building4', 'building5', 'building10' ]

Note: This is better than the other solutions posted till now, as this will work fine even if the numbers are greater than 9.

Use .sort() method

var a = ['building2', 'building1' , 'building3', 'building5', 'building4'];
console.log(a.sort());

Output

["building1", "building2", "building3", "building4", "building5"] 

Is not needed a custom function

Array.sort , using:

['building2', 'building1', 'building3', 'building5', 'building4']. 
  sort(function(a,b){
         return +( /\d{1,}$/.exec(a) || [0] )[0] - 
                +( /\d{1,}$/.exec(a) || [0] )[0]; 
       }
  );

That way you can also sort on more then 10 buildings like in
['building1', 'building12', 'building302', 'building205', 'building400']
and include strings not ending with numeric values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM