很抱歉,我有一个问题要找&解决一道数学题

假设我有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相关问答推荐

如何在JavaScript中通过一次单击即可举办多个活动

如何将拖放功能添加到我已自定义为图像的文件输入HTML标签中?

RxJS setTimeout操作符等效

微软Edge Select 间隙鼠标退出问题

Redux查询多个数据库Api reducerPath&

未定义引用错误:未定义&Quot;而不是&Quot;ReferenceError:在初始化&Quot;之前无法访问';a';

Web Crypto API解密失败,RSA-OAEP

为什么我的自定义元素没有被垃圾回收?

在开发期间,Web浏览器如何运行&qot;.jsx&qot;文件?

Reaction组件在本应被设置隐藏时仍显示

匹配一个或多个可选重复的特定模式

无法重定向到Next.js中的动态URL

在JavaScript中,有没有一种方法可以迭代字符串的词法标记?

TabNavigator和StackNavigator之间的Reaction Native中的导航问题

如何用react组件替换dom元素?

在此div中添加一个类,并在一段时间后在Java脚本中将其删除

MAT-TREE更多文本边框对齐问题

带元素数组的Mongo聚合

如何在Java脚本中添加一个可以在另一个面板中垂直调整大小的面板?

在不使用AJAX的情况下将JavaScript数组值传递给Laravel控制器?