很抱歉,我正在尝试查找并解决一道数学题
假设我有 2 个列表或数组
内容数组
0-50 = C1
50-100 = C2
广告数组
10-20 = A1
30-60 = A2
80-140 = A3
输出应该是这样的
0-10 = C1
10-20 = A1
20-30 = C1
30-60 = A2
60-80 = C2
80-100 = A3
此处广告正在替换实际内容并将内容拆分为一组新的项目。
const content = [
{start: 0, end: 50, id: 'C1'},
{start: 50, end: 100, id: 'C2'},
]
const ad = [
{start:10, end: 20, id: 'A1' },
{start:30, end: 60, id: 'A2' },
{start:80, end: 140, id: 'A3' },
]
const newList = []
content.forEach(content => {
ad.forEach((ad, index) => {
//0 > 0 && 20 < 50
if(content.start < ad.start && content.end > ad.end){
newList.push({start: content.start, end: ad.start, id: content.id})
newList.push(ad)
}else{
console.log(decodeURIComponent(`${content.start} > ${ad.start} && ${content.end} < ${ad.end}`))
}
})
})
console.log('newList',newList)
请帮忙
最佳答案
其实,我不知道我能对代码说些什么,试试这个方法:
const content = [{start: 0, end: 50, id: 'C1'},{start: 50, end: 100, id: 'C2'}];
const ad = [{start:10, end: 20, id: 'A1' },{start:30, end: 60, id: 'A2' },{start:80, end: 140, id: 'A3' }];
const cPoints = content.flatMap(e => [e.start, e.end]); // [0, 50, 50, 100]
const aPoints = ad.flatMap(e => [e.start, e.end]); // [10, 20, 30, 60, 80, 140]
const rangeMin = Math.min(...cPoints); // 0
const rangeMax = Math.max(...cPoints); // 100
const rangePoints = [...new Set([...aPoints, ...cPoints])] // [10, 20, 30, 60, 80, 140, 0, 50, 100]
.filter(point => (point >= rangeMin) && (point <= rangeMax)) // [10, 20, 30, 60, 80, 0, 50, 100]
.sort((a, b) => a - b); // [0, 10, 20, 30, 50, 60, 80, 100]
const getObjByPoint = (point, arr) =>
arr.find((e) => (e.start <= point) && (point <= e.end));
const getFirstId = (point) =>
(getObjByPoint(point, ad) || getObjByPoint(point, content)).id;
const result = rangePoints.reduce((acc, end, index, arr) => {
if (index === 0) return acc;
let start = arr[index - 1];
const middle = (start + end) / 2;
const id = getFirstId(middle);
if (acc.at(-1)?.id === id) {
start = acc.pop().start;
}
acc.push({ start, end, id });
return acc;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 时间转换器 : split content time with ads time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71871954/