关于数组拆分的问题?
像这样的数组,如何才能拆分为结果图所示的那样,将时间不连贯的拆开为单独的一项
结果图
回答
const result = {};const arr = [
{ time: '10:00' },
{ time: '11:00' },
{ time: '12:00' },
{ time: '13:00' },
{ time: '17:00' },
{ time: '18:00' },
{ time: '19:00' },
{ time: '20:00' },
{ time: '21:00' },
{ time: '23:00' },
{ time: '22:00' },
];
const splitNum = 1; //间隔超过1个小时就认为不连续
let partNum = 1;
arr.sort((a, b) => parseInt(a.time) - parseInt(b.time)).map((value, index) => {
if (index === 0) {
result[`part_${partNum}`] = [value];
return
}
if (parseInt(value.time) - parseInt(arr[index - 1].time) > splitNum) {//不连续
partNum += 1;
result[`part_${partNum}`] = [];
}
result[`part_${partNum}`].push(value);
})
console.log(result);
// {
// part_1: [
// { time: '10:00' },
// { time: '11:00' },
// { time: '12:00' },
// { time: '13:00' }
// ],
// part_2: [
// { time: '17:00' },
// { time: '18:00' },
// { time: '19:00' },
// { time: '20:00' },
// { time: '21:00' },
// { time: '22:00' },
// { time: '23:00' }
// ]
// }
const foo = (res) => res.map((cur) => Number(cur.time.split(':')[0]))
.reduce((acc, curTime, i, src) => {
const cur = res[i];
// 与上一个元素不衔接
if (!src[i - 1] || curTime - 1 > src[i - 1]) {
acc.push([cur]);
} else {
acc[acc.length - 1].push(cur);
}
return acc;
}, []);
// 测试
> foo([{ time: '10:00' }, { time: '11:00' }, { time: '12:00' }, { time: '13:00' }, { time: '17:00' }, { time: '18:00' }, { time: '20:00' }, { time: '22:00' }, { time: '23:00' }]);
< [
[{ time: "10:00" }, { time: "11:00" }, { time: "12:00" }, { time: "13:00" }],
[{ time: "17:00" }, { time: "18:00" }],
[{ time: "20:00" }],
[{ time: "22:00" }, { time: "23:00" }]
];
和上一次答的有那么一些神似。
以上是 关于数组拆分的问题? 的全部内容, 来源链接: utcz.com/a/39912.html