Skip to content
Advertisement

Find upper and lower boundaries in array

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?

Advertisement

Answer

You could check the previous value and next value and filter the array.

const
    getLowerUpper = (array, pivot) => array
        .filter((v, i, { [i - 1]: prev, [i + 1]: next }) =>
            v <= pivot && next > pivot ||
            prev <= pivot && v >= pivot ||
            prev === undefined && next > pivot ||
            prev < pivot && next === undefined
        ),
    boundaries = [15, 30, 45, 60, 75, 90];

console.log(...getLowerUpper(boundaries, 22));  // between
console.log(...getLowerUpper(boundaries, 30));  // direct and next
console.log(...getLowerUpper(boundaries, 10));  // lowest
console.log(...getLowerUpper(boundaries, 15));  // direct and next
console.log(...getLowerUpper(boundaries, 90));  // highest
console.log(...getLowerUpper(boundaries, 100)); // highest
Advertisement