在字符串数组中,如何对部分字符串进行排序 [英] In an array of strings how to sort the array on part of the strings

查看:85
本文介绍了在字符串数组中,如何对部分字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以为可能有一种方法可以使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆