鉴于下面的数组已经按“startDate”排序,我试图比较哪些对象在前一个对象“endDate”之后出现“startDate”。
overlapList = [
{elem: <div id="task7">, startDate: 918, endDate: 1053, order: 1}
{elem: <div id="task8">, startDate: 973, endDate: 1108, order: 2}
{elem: <div id="task3">, startDate: 1026, endDate: 1647, order: 3}
{elem: <div id="task6">, startDate: 1053, endDate: 1188, order: 4}
{elem: <div id="task5">, startDate: 1107, endDate: 1242, order: 5}
{elem: <div id="task4">, startDate: 1188, endDate: 1323, order: 6}
]
如果为true,则更新比较对象的订单号以匹配。所需的输出是:
overlapList = [
{elem: <div id="task7">, startDate: 918, endDate: 1053, order: 1}
{elem: <div id="task8">, startDate: 973, endDate: 1108, order: 2}
{elem: <div id="task3">, startDate: 1026, endDate: 1647, order: 3}
{elem: <div id="task6">, startDate: 1053, endDate: 1188, order: **1**}
{elem: <div id="task5">, startDate: 1107, endDate: 1242, order: **2**}
{elem: <div id="task4">, startDate: 1188, endDate: 1323, order: **1**}
]
当对象添加到数组中时,脚本会查看给定“order”的最大“endDate”数字。
我认为最好的方法是动态添加到第二个数组(maxOrderEnd),以便与第一个跟踪max“endDate”和相应“order”的数组进行比较。
“if”语句将始终首先查看最小的“order”数,以确定对象的“startDate”是否大于“order”“endDate”。如果为false,它将移动到下一个“订单”号并进行比较。如果没有符合条件的现有“订单”编号是“maxOrderEnd”数组,则会在“maxOrderEnd”数组中添加一个新的“订单”编号。
鉴于上面的“overlapList”数组,“maxOrderEnd”数组的最终结果将是:
maxOrderEnd = [
{endDateMax: 0, order: 0}
{endDateMax: 1323, order: 1}
{endDateMax: 1242, order: 2}
{endDateMax: 1647, order: 3}
]
我尝试编写以下脚本但仍然遇到订单循环问题:
for (var i = 0; i < overlapList.length; i++){
maxOrderEnd = [{endDateMax: 0, order: 0}];
overlapList.forEach(function(start){
var addOrder = 0;
for (var i = 0; i < maxOrderEnd.length; i++){
var less = maxOrderEnd.filter(function(item){ return start.startDate + 1 > item.endDateMax})[i];
if (less){
maxOrderEnd.push({endDateMax: start.endDate, order: addOrder}),
addOrder = addOrder + 1;
}
else {start.order = maxOrderEnd.order, maxOrderEnd.endDateMax = start.endDate;
}
console.log(addOrder);
}
});
}
console.log(overlapList);
console.log(maxOrderEnd);