简体   繁体   中英

In an array of strings how to sort the array on part of the strings

I was beginning to write a bubble sort for this when I thought maybe there is a way to use a function with array.sort() that does the job ?

Here is a (hopefully) clear example of what I have to sort : (file names list)

var array = ['impression_page_1_12_juin','impression_page_1_13_juin','impression_page_2_12_juin','impression_page_2_13_juin']

As you can see there are 2 'page1' on 2 different dates, only characters 19 and 20 in each string are different. I'd like to sort on those 2 characters.

Can Javascript do that straightforward or should I return to my substrings and bubble sort method ?

Use the sort method with a function for the comparison:

array.sort(function(x,y){
  var xp = x.substr(18, 2);
  var yp = y.substr(18, 2);
  return xp == yp ? 0 : xp < yp ? -1 : 1;
});

Yes, you can pass a function to array.sort that compares the two strings according to whatever criteria you're interested in. See How to sort array in javascript?

You will have to be careful with strings vs. numbers: '1_12' < '1_2' is True , for instance. If you need to compare them as numbers, you could split the strings, do parseInt on each part, and implement a pairwise comparison.

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