[09.02.2017 - 10:40:06][NOTICE] - Start looping through invoices from Teamleader..
[08.02.2017 - 10:24:26][NOTICE] - Start looping through invoices from Teamleader..
[08.02.2017 - 10:29:24][NOTICE] - Start looping through invoices from Teamleader..
这是产生上述输出的代码:
var data = allText.split("\n");
for(var i = 0, len = data.length; i < len; i++){
console.log(data[i]);
}
是否可以在给定的日期和时间对数组进行排序?
以下是它应该如何显示的示例:
[09.02.2017 - 10:40:06][NOTICE] - Start looping through invoices from Teamleader..
[08.02.2017 - 10:29:25][NOTICE] - Start looping through invoices from Teamleader..
[08.02.2017 - 10:24:26][NOTICE] - Start looping through invoices from Teamleader..
答案 0 :(得分:3)
在撰写本文时,其他解决方案要么不完整,要么包含错误。特别是,accepted answer by rakwaht将日期排序为字符串,这会产生不正确的结果。
您可以使用正则表达式和Date
构造函数从行中提取和解析日期。从那里开始,只需要对包含这些行的数组进行排序:
const data = `
[09.02.2017 - 10:40:06][NOTICE] - Start looping through invoices from Teamleader..
[08.02.2017 - 10:24:26][NOTICE] - Start looping through invoices from Teamleader..
[08.02.2017 - 10:29:24][NOTICE] - Start looping through invoices from Teamleader..`
.trim().split('\n')
function dateFromLine(line) {
const result = /^\[(.*?)\]/.exec(line)
const date = result[1].replace("-", "")
return new Date(date)
}
function compareLinesByDate(a, b) {
return dateFromLine(b) - dateFromLine(a)
}
data.sort(compareLinesByDate)
console.log(data.join('\n'))
&#13;
请注意,此代码假定每行都以这种方式格式化。为了使其更加健壮,还需要做更多的工作。
答案 1 :(得分:1)
您可以使用sort函数对数组进行排序,您可以在其中指定应对其进行排序的基数:
这是一个符合您需求的示例:
var data = [
"[09.02.2017 - 10:40:06][NOTICE] - Start looping through invoices from Teamleader]",
"[08.02.2017 - 10:24:26][NOTICE] - Start looping through invoices from Teamleader]",
"[08.02.2017 - 10:29:24][NOTICE] - Start looping through invoices from Teamleader]"
];
data.sort(
function(a, b){
// a and b are two elements in the list that are supposed to be compared
var a_date = a.substring(1, 22); //take only date from string
var b_date = b.substring(1, 22); //take only date from string
// We compare those strings to order it.
if ( a_date < b_date )
return 1;
if ( a_date > b_date )
return -1;
return 0;
}
);
console.log(data);
&#13;
YouTube Data API - Errors你可以在JS中找到对sort函数的一些引用
答案 2 :(得分:0)
您可以使用数组中的函数sort()
和比较函数来比较日期。我不知道你要比较什么,但这是一个简单的例子。
[/*...*/].sort(function(a, b){
//here a and b stand for your dates. you will need to adjuste your code to make it works since we have very little information about it.
return Date.compare(a, b);
});
答案 3 :(得分:0)
好吧,如果我必须这样做,我会在一个真实的数组中转换它然后使用这样的函数:
function SortByDate(a, b){
var aDateField = a.DateField.toLowerCase();
var bDateField = b.DateField.toLowerCase();
return ((aDateField < bNDateField) ? -1 : ((aDateField > bDateField) ? 1 : 0));
}
var data = allText.split("\n");
for(var i = 0, len = data.length; i < len; i++){
//construct your array_data here
}
var dataSortByDate = array_data.sort(SortByDate);
这是我经常使用的比较功能之一。希望它会有所帮助。