gpt4 book ai didi

javascript - 如何合并间距数组

转载 作者:行者123 更新时间:2023-11-30 06:19:22 24 4
gpt4 key购买 nike

有一个区间数组,需要组合重叠,即:

[[0, 33], [66, 80]] => [[0, 33], [66, 80]]

[[0, 33], [66, 80], [0, 66], [33, 100]] => [0,100]

写代码。我得到结果 [[0, 100], [66, 80]]。这是因为首先范围 [[0, 33]], 然后 [[0, 33], [66, 80]], 然后 [[0, 66], [66, 80]], 然后 [[0, 100] , [66, 80]] 好像在不循环的情况下检查其他范围

const data = [
[0, 33],
[66, 80],
[0, 66],
[33, 100]
];

createDataForSlider = data =>
data.reduce((prevVal, time) => {
let isPrevValUpdated = false;

const timeStart = time[0];
const timeEnd = time[1];

/* eslint no-param-reassign: ["error", { "ignorePropertyModificationsFor": ["prevVal"] }] */
if (prevVal.length) {
for (let i = 0, ii = prevVal.length; i < ii; i += 1) {
let prevValCurrent = prevVal[i];

if (timeStart >= prevValCurrent[0] && timeEnd <= prevValCurrent[1]) {
isPrevValUpdated = true;
break;
}
if (
!isPrevValUpdated &&
timeStart >= prevValCurrent[0] &&
timeStart <= prevValCurrent[1]
) {
prevValCurrent[1] = timeEnd;
isPrevValUpdated = true;
break;
}
if (
!isPrevValUpdated &&
timeEnd >= prevValCurrent[0] &&
timeEnd <= prevValCurrent[1]
) {
prevValCurrent[0] = timeStart;
isPrevValUpdated = true;
break;
}

//console.log("prevVal-", prevVal);
}
}
if (!isPrevValUpdated) {
prevVal.push([timeStart, timeEnd]);
}
return prevVal;
}, []);

createDataForSlider(data);

最佳答案

尝试跟随

  1. 根据所有开始时间对数组进行排序
  2. 现在,通过将先前插入的频率与当前频率进行比较,使用空数组累加器对其进行归约。

    const frequencies = [[0, 33], [66, 80], [0, 66], [33, 100]];

    const sortedFrequencies = frequencies.sort((f1, f2) =>{ return f1[0] - f2[0]});

    sortedFrequencies.reduce((acc, current) => {
    if(acc.length > 0 && current[0] <= acc[acc.length - 1][1]) {

    acc[acc.length - 1][1] = current[1] > acc[acc.length - 1][1] ? current[1] : acc[acc.length - 1][1];
    } else {

    acc.push(current)
    }
    return acc;
    }, []);

关于javascript - 如何合并间距数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54109608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com