I'm currently working on extracting the upper and lower boundaries for a numeric
value within an array.
const boundaries = [15, 30, 45, 60, 75, 90];
const age = 22;
In the given example, the expected result would be:
[15, 30]
If the value matches a boundary, it will be considered the lower
value in the resulting array. If it is equal to or exceeds the maximum boundary, it will be taken as the maximum value.
Examples of possible outcomes:
15 => [15, 30]
22 => [15, 30]
30 => [30, 45]
90 => [90]
I attempted to achieve this by iterating over the array using mapping
, checking if the age
surpasses a boundary => and then determining the relevant boundary. Despite that, I am uncertain if this is the most effective approach.
const boundaries = [15, 30, 45, 60, 75, 90];
const age = 22;
// obtain all lower values
const allLower = boundaries.map((b) => age > b ? b : null).filter(x => x);
const lower = allLower[allLower.length - 1]; // retrieve lowest
const upper = boundaries[boundaries.indexOf(lower) + 1]; // get next
const result = [lower, upper]; // construct result
console.log(result);
Is there an alternative method that is concise
/ more efficient
/ reliable
for this task?