gpt4 book ai didi

javascript - 如何根据范围过滤数组,然后在结果的两侧获取额外的样本

转载 作者:行者123 更新时间:2023-11-28 16:56:53 25 4
gpt4 key购买 nike

我正在寻找以下示例的简单解决方案:

let rangeOfInterest = [25 , 44];
let input = [10, 20, 30, 40, 50, 60];

我对大于 25 且小于 44(含)的所有值感兴趣。 rangeOfInterest 可能完全在输入值内部或完全外部,其他示例包括 [85, 95] 或 [0, 100]。

output1 = [30, 40];

如果此输出的任一侧都存在值,则也获取该样本;

finalOutput = [20, 30, 40, 50];

我可以通过对数组应用过滤器,然后查找结果的第一个和最后一个元素的索引并基于该索引提取附加样本(如果存在)来实现上述目的。有没有一种更简洁的方法来实现这一目标,而不需要大约 20 行代码?

注意:样本将是 float ,使用整数作为更简单的示例。

最佳答案

可以找到第一个大于最小范围的项的索引,以及第一个大于最大范围的项的索引,并根据索引进行切片(minIndex - 1, maxIndex + 1) .

const fn = ([min, max], arr) => {
const startIndex = arr.findIndex(n => n > min); // find the index of the first item that is larger than min
const endIndex = arr.findIndex(n => n > max); // find the index of the first item that is smaller than max

return arr.slice(
startIndex > 1 ? startIndex - 1 : 0,
endIndex === -1 ? arr.length : endIndex + 1
);
};


const input = [10, 20, 30, 40, 50, 60];

console.log(fn([25 , 44], input));

console.log(fn([25 , 65], input));

console.log(fn([-25 , 65], input));

关于javascript - 如何根据范围过滤数组,然后在结果的两侧获取额外的样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913022/

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