在字符串数组中,如何对部分字符串进行排序 [英] In an array of strings how to sort the array on part of the strings
问题描述
当我以为可能有一种方法可以使用array.sort()函数来完成工作时,我就开始为此进行冒泡排序了.
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']
如您所见,在2个不同的日期有2个"page1",每个字符串中只有19和20个字符是不同的.我想对这两个字符进行排序.
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.
JavaScript可以做到这一点吗?还是应该返回子字符串和冒泡排序方法?
Can Javascript do that straightforward or should I return to my substrings and bubble sort method ?
推荐答案
将sort
方法与函数进行比较:
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;
});
这篇关于在字符串数组中,如何对部分字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!