简体   繁体   English

在字符串数组中,如何在字符串的一部分上对数组进行排序

[英]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 ? 当我想也许有一种方法可以使用array.sort()来完成这项工作时,我开始为此编写一个冒泡排序?

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. 正如您所看到的,在2个不同日期有2个'page1',每个字符串中只有字符19和20不同。 I'd like to sort on those 2 characters. 我想对这2个字符进行排序。

Can Javascript do that straightforward or should I return to my substrings and bubble sort method ? Javascript可以直截了当地执行,还是应该返回到我的子串和冒泡排序方法?

Use the sort method with a function for the comparison: 使用带有函数的sort方法进行比较:

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? 是的,您可以将函数传递给array.sort,根据您感兴趣的条件比较两个字符串。请参阅如何在javascript中对数组进行排序?

You will have to be careful with strings vs. numbers: '1_12' < '1_2' is True , for instance. 你必须小心字符串与数字: '1_12' < '1_2'True ,例如。 If you need to compare them as numbers, you could split the strings, do parseInt on each part, and implement a pairwise comparison. 如果您需要将它们作为数字进行比较,您可以拆分字符串,对每个部分执行parseInt,并实现成对比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM