查找数组的上边界和下边界

axt*_*tck 4 javascript arrays

numeric我正在尝试获取数组中值的上限和下限。

const boundaries = [15, 30, 45, 60, 75, 90];
const age = 22;
Run Code Online (Sandbox Code Playgroud)

对于上面的例子,结果应该是:

[15, 30]
Run Code Online (Sandbox Code Playgroud)

例如,如果该值是边界,它将成为lower结果数组中的值。如果它是最大边界或以上,它应该成为最大值。

结果示例:

15 => [15, 30]
22 => [15, 30]
30 => [30, 45]
90 => [90]
Run Code Online (Sandbox Code Playgroud)

我尝试mapping通过数组,如果age更高=> return boundary。然后filter超出边界并计算索引,但这感觉不是完成此任务的正确方法。

const boundaries = [15, 30, 45, 60, 75, 90];
const age = 22;

// get all lower values
const allLower = boundaries.map((b) => age > b ? b : null).filter(x => x);
const lower = allLower[allLower.length - 1]; // get lowest
const upper = boundaries[boundaries.indexOf(lower) + 1]; // get next

const result = [lower, upper]; // form result

console.log(result);
Run Code Online (Sandbox Code Playgroud)

有没有办法shorter做到这一点?bettermore reliable

Nic*_*ase 5

为什么要使用索引呢?如果boundaries数组没有排序怎么办?allLower将列表过滤为and allUpper(包含低于和高于阈值的值),然后在结果数组上使用minand不是更容易吗?max


示例代码:

const boundaries = [15, 30, 45, 60, 75, 90];
const age = 22;

const allLower = boundaries.filter(x => x < age);
const allUpper = boundaries.filter(x => x > age);

const lowerBound = Math.max(...allLower);
const upperBound = Math.min(...allUpper);
Run Code Online (Sandbox Code Playgroud)