5

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 ?

5
  • characters 17, 19, and 20 are different in each string. Commented Jun 13, 2012 at 14:18
  • You're right... but I wanted to group the 'date' part in the list... page numbers are already sorted. Thanks for nailing it ;-) Commented Jun 13, 2012 at 14:49
  • this isn't a google-apps-script question ... Commented Jun 13, 2012 at 15:02
  • @Edo, sorry, my question was tagged javascript and GAS, I don't think this is really off topic, do you ? Commented Jun 13, 2012 at 15:08
  • it's not a big deal but I don't get how this question can be related to GAS ... Commented Jun 13, 2012 at 15:15

2 Answers 2

14

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

jeee, that's fast ! and when I see it I find it cristal clear ;-) thanks
I adjusted this for my use, and while it works for a small array (<10 entries), it doesn't for a larger array (70-100 entries), and I don't quite understand why. Is there something I can adjust for it to work for a larger array?
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.