例程:对象数组的二维比较和插入
/**
* 例程:对象数组的二维比较和插入
* Author: pockry
* 说明:需要插入的数组已经是排序好的
*/
var arr = [
{y: 2014, m: 10},
{y: 2014, m: 7},
{y: 2014, m: 1},
{y: 2013, m: 7},
{y: 2013, m: 1}
];
var newarr = {y: 2013, m: 10};
for (var i = 0; i < arr.length; i++) {
document.write("y: " + arr[i].y + " m: " + arr[i].m + "<br />")
}
if (arr[0].y < newarr.y) {
arr.splice(0, 0, newarr);
} else if (arr[arr.length - 1].y > newarr.y) {
arr.push(newarr);
} else {
for (var i = 0; i < arr.length; i++) {
if (arr[i].y == newarr.y) {
if (arr[i].m < newarr.m) {
arr.splice(i, 0, newarr);
break;
} else if (arr[i + 1].y < newarr.y || arr[i + 1].m < newarr.m) {
arr.splice(i + 1, 0, newarr);
break;
}
}
}
}
document.write("<br><br>");
for (var i = 0; i < arr.length; i++) {
document.write("y: " + arr[i].y + " m: " + arr[i].m + "<br />");
}