我正在分析日志文件,我希望通过降序排序请求,使其更容易阅读。问题是我有一个二维数组,每个都有一个对象,我想通过它们的一个对象属性(这里的平均响应时间)对数组进行排序,我不知道如何访问它......
以下是最终日志文件的一部分供您理解:
[
[
{
"Request": "/sql/sqlweb/",
"Average response time": "2.685 ms",
"Number of calls": 1
}
],
[
{
"Request": "/",
"Average response time": "1.219 ms",
"Number of calls": 2529
}
],
[
{
"Request": "/mysql/admin/",
"Average response time": "4.086 ms",
"Number of calls": 1
}
],
[
{
"Request": "/mysql/sqlmanager/",
"Average response time": "2.774 ms",
"Number of calls": 1
}
],
[
{
"Request": "/phpmyadmin/",
"Average response time": "2.417 ms",
"Number of calls": 2
}
]
]
这是在我的数组上的JSON.stringify()之后。如果需要,我也可以复制/粘贴当前版本的代码。
Ps:如果有帮助,我可以轻松删除“ms”。
答案 0 :(得分:1)
您可以使用sort()
,您可以编写一个比较器函数,在该函数中使用平均响应时间比较数组内的对象,为此您可以使用parseFloat()
var arr = [
[
{
"Request": "/sql/sqlweb/",
"Average response time": "2.685 ms",
"Number of calls": 1
}
],
[
{
"Request": "/",
"Average response time": "1.219 ms",
"Number of calls": 2529
}
],
[
{
"Request": "/mysql/admin/",
"Average response time": "4.086 ms",
"Number of calls": 1
}
],
[
{
"Request": "/mysql/sqlmanager/",
"Average response time": "2.774 ms",
"Number of calls": 1
}
],
[
{
"Request": "/phpmyadmin/",
"Average response time": "2.417 ms",
"Number of calls": 2
}
]
];
arr.sort(function(a,b){
return parseFloat(a[0]["Average response time"]) - parseFloat(b[0]["Average response time"]);
});
console.log(arr);
答案 1 :(得分:0)
你可以获取内部数组的第一个对象,然后获取想要的属性进行排序。
var array = [[{ Request: "/sql/sqlweb/", "Average response time": "2.685 ms", "Number of calls": 1 }], [{ Request: "/", "Average response time": "1.219 ms", "Number of calls": 2529 }], [{ Request: "/mysql/admin/", "Average response time": "4.086 ms", "Number of calls": 1 }], [{ Request: "/mysql/sqlmanager/", "Average response time": "2.774 ms", "Number of calls": 1 }], [{ Request: "/phpmyadmin/", "Average response time": "2.417 ms", "Number of calls": 2 }]];
array.sort(function (a, b) {
function getV(o) {
return o[0]['Average response time'].match(/\d+\.?\d*/);
}
return getV(b) - getV(a);
});
console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)
你可以这样做:
[
[
{
"Request": "/sql/sqlweb/",
"Average response time": "2.685 ms",
"Number of calls": 1
}
],
[
{
"Request": "/",
"Average response time": "1.219 ms",
"Number of calls": 2529
}
],
[
{
"Request": "/mysql/admin/",
"Average response time": "4.086 ms",
"Number of calls": 1
}
],
[
{
"Request": "/mysql/sqlmanager/",
"Average response time": "2.774 ms",
"Number of calls": 1
}
],
[
{
"Request": "/phpmyadmin/",
"Average response time": "2.417 ms",
"Number of calls": 2
}
]
].sort(function(a, b) {
return Number(a[0]["Average response time"].replace(/[^0-9]+/g, "")) - Number(b[0]["Average response time"].replace(/[^0-9]+/g, ""));
});
答案 3 :(得分:0)
您需要将array.sort与自定义比较器一起使用。