[英]Javascript/jQuery nested array sort
I have array like this: 我有这样的数组:
var arr = [
["2013/09/09", 1, 2],
["2013/12/31", 2, 5],
["2014/12/30", 1, 4],
["2013/04/17", 1, 1]
];
I need to sort this array according to date present in each of the sub-arrays. 我需要根据每个子数组中存在的日期对该数组进行排序。
ex. 例如
var sorted = [
["2013/04/17", 1, 1],
["2013/09/09", 1, 2],
["2013/12/31", 2, 5],
["2014/12/30", 1, 4]
];
Try this, 尝试这个,
var arr = [
["2013/09/09", 1, 2],
["2013/12/31", 2, 5],
["2014/12/30", 1, 4],
["2013/04/17", 1, 1]
];
var temp;
for(var i=0;i<arr.length;i++)
{
for(var j=0;j<arr.length;j++)
{
var di = new Date(arr[i][0]);
var dj = new Date(arr[j][0]);
if(di < dj)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
If you are sorting large arrays, its better to do a date conversion just once, rather than repeating the creation on every jiggle of the sort routine. 如果要对大型数组进行排序,最好只进行一次日期转换,而不是在排序例程的每个微动上重复创建。
function unaturalSort(arr){
var T= arr.slice(0), L= T.length, i, itm, next;
// create a timestamp for each element
for(i= 0; i<L; i++){
itm= T[i];
next= T[i][0];
T[i]= [+new Date(next), itm];
}
T.sort(function(a, b){
return a[0]-b[0]
});
//remove the timestamps from the sorted array
for(i= 0; i<L; i++){
T[i]= T[i][1];
}
return T;
}
var A= [
["2013/09/09", 1, 2], ["2013/12/31", 2, 5],
["2014/12/30", 1, 4],["2013/04/17", 1, 1]
];
unaturalSort(A).join('\n');
returned value: (String)
2013/04/17, 1, 1
2013/09/09, 1, 2
2013/12/31, 2, 5
2014/12/30, 1, 4
Note- skip the slice(), if you mean to rearrange the existing array. 注意-如果要重新排列现有数组,请跳过slice()。
Use of native sort
and parseInt
which I believe I am the most short hand among the other answers: 我相信我是其他答案中最短手的使用本机
sort
和parseInt
:
function sortDate (a,b){
return parseInt(a[0].split("/").join("")) - parseInt(b[0].split("/").join(""));
}
var arr = [
["2013/09/09", 1, 2],
["2013/12/31", 2, 5],
["2014/12/30", 1, 4],
["2013/04/17", 1, 1]
];
var result = arr.sort(sortDate)
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.