I am trying to get the upper and lower boundaries of a numeric value in an array.
const boundaries = [15, 30, 45, 60, 75, 90];
const age = 22;
For the above example, the outcome should be:
[15, 30]
If for example the value is a boundary, it would become the lower value in the outcome array. If it is the max boundary or above, it should become the max value.
Example outcomes:
15 => [15, 30]
22 => [15, 30]
30 => [30, 45]
90 => [90]
I tried mapping through the array and if the age is higher => return boundary. Then filter out the boundaries and calculate the indexes, but this doesn't feel like the correct way to accomplish this.
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);
Is there a shorter / better / more reliable way to do this?