Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 990
Serge insas Avatar asked Jun 13 '12 14:06

Serge insas


People also ask

How do you sort part of an array?

Arrays. sort() method can be used to sort a subset of the array elements in Java. This method has three arguments i.e. the array to be sorted, the index of the first element of the subset (included in the sorted elements) and the index of the last element of the subset (excluded from the sorted elements).

How do you sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.

How do you sort an array of arrays?

To sort an array of arrays in JavaScript, we can use the array sort method. We call array. sort with a callback that destructures the first entry from each nested array. Then we return the value to determine how it's sorted.


1 Answers

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;
});
like image 150
Guffa Avatar answered Sep 27 '22 22:09

Guffa