Locate the upper and lower limits within an array

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?

Answer №1

What is the reasoning behind utilizing indices in this scenario? Have you considered the possibility of the boundaries array being unsorted? Perhaps it would be more straightforward to segregate the values into allLower and allUpper (containing values below and above the threshold), and then utilize min and max on the resulting arrays instead?


Here is a sample code snippet:

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);

Answer №2

Using the reduce method seems like a suitable solution in this scenario:

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


for (let search of [1, 22, 30, 90, 100]) {

    let [low, upr] = boundaries.reduce(([low, upr], x) =>
        [
            x <= search ? Math.max(low, x) : low,
            x >  search ? Math.min(upr, x) : upr,

        ],
        [-Infinity, +Infinity]
    )

    console.log(low, '<=', search, '<', upr)

}

This particular approach does not necessitate the sorting of boundaries. However, if they are always sorted, you may want to consider implementing binary search to find the lower bound.

Answer №3

Perhaps considering a simple for-loop can be beneficial in this situation ;)

function determineAgeBounds(age) {
  for (let index = 0; index < ageBoundaries.length; index++) {
    if (ageBoundaries[index] <= age && (ageBoundaries[index + 1] ?? Infinity) > age) {
      return ageBoundaries.slice(index, index + 2);
    }
  }
}

Answer №4

To identify the previous and next values, you can apply a filter function to the array.

const
    findNeighbours = (arr, middle) => arr
        .filter((val, index, { [index - 1]: prev, [index + 1]: next }) =>
            val <= middle && next > middle ||
            prev <= middle && val >= middle ||
            prev === undefined && next > middle ||
            prev < middle && next === undefined
        ),
    limits = [18, 36, 54, 72, 90];

console.log(...findNeighbours(limits, 22));  // in between
console.log(...findNeighbours(limits, 36));  // directly above and below
console.log(...findNeighbours(limits, 10));  // lowest value 
console.log(...findNeighbours(limits, 18));  // directly above and below
console.log(...findNeighbours(limits, 90));  // highest value
console.log(...findNeighbours(limits, 100)); // highest value

Answer №5

To simplify the array, you can do something along these lines:

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

const getResult = (array, target) => {
  if (target < array[0] || target > array[array.length - 1]) {
    return [];
  }
  return array.reduce((a, c) => {
    if (c <= target) {
      a[0] = c;
    } else if (c > target && (!a[1] || c < a[a.length - 1])) {
      a[a.length] = c;
    }
    return a;
  }, []);
}

console.log(getResult(boundaries, 22));
console.log(getResult(boundaries, 15));
console.log(getResult(boundaries, 30));
console.log(getResult(boundaries, 90));
console.log(getResult(boundaries, 14));
console.log(getResult(boundaries, 91));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get information from the server via an ajax callback without refreshing the page and dynamically refresh the current page content. Node.js and Express 4

I am trying to implement a form and an Ajax client script that sends the form data to Express. The code for the form looks like this: form#form-reflow(action='/', method='post', onsubmit="docreflow()") input#te ...

Encountered an npm compilation error - Unable to locate module: bootstrap-theme.css

I recently updated all the dependencies in my JavaScript program without making any changes to my components or index.js file. However, when I run npm run build I encounter an error with index.js related to bootstrap-theme.css: Failed to compile. Modul ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

What occurs when Render() is called during animation in React?

Curious about how React handles rendering during a component's animation? Let's explore an example where a component is re-rendered due to a state change triggered during its animation. Imagine a scenario where a component's animation lasts ...

What are the steps for initializing a 2D Boolean Array?

I'm currently working on a problem that involves dealing with arrays, and I'm finding it quite challenging to combine booleans with arrays and organize them properly. The code below is incorrect, and I'm unsure about how to proceed. Here are ...

Cannot locate module: Unable to resolve 'encoding' in '/Users/dev/node_modules/node-fetch/lib'

Currently, I am working with next.js version 13.4.5 and firebase version 10.1.0. Every time I execute npm run dev, a warning is displayed initially. Eventually, an error message pops up in the terminal after the warning persists for some time. I am u ...

Dismiss Bootstrap by clicking anywhere

I have a specific input that is displayed when clicked and disappears with the next click: <a href="#;" class="asset_info" data-asset_id="{{ asset.pk }}" data-toggle="focus" tabindex="0" data-placement="left" data-trigger="focus" >Hello</a> ...

Working with a two-dimensional array in Java: printing values using a for loop

I'm attempting to create a two-dimensional for loop that will display the following pattern: 7 5 3 1 2 4 6 8 Below is my array: int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}}; The current for loop provided only prints one number ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...

How can Swipe support help you slide a menu back in?

For implementing swipe support on my landing page carousel, I included jquery.mobile.custom.min.js. However, I am facing a challenge with adding swipe support to "close" the menu. Essentially, swiping left should have the same effect as clicking the butto ...

Having difficulty accessing node_modules directory in JavaScript

I am confused about how to access node_modules for JavaScript. Can someone provide an example of calling module.exports from a node_module folder after installing a package with NPM in Node.js? File tree structure: There is a folder named 'ethereum&a ...

The menu is loaded dynamically by Ajax from JavaScript once the page is refreshed

$('#subregionListPage').bind('pageinit', function(event){ var output = $('#subregions'); var region = getUrlVars()["reg"]; $.ajax({ url: 'http://localhost:8888/my/getsubregions.php', dat ...

Unleashing the Array within a JavaScript Object

Currently, I am successfully receiving messages from a Server via Websocket. The received messages are in the form of a Javascript Object, and my goal is to extract the necessary data from it and update the state of my React app accordingly. Here is the c ...

Event Triggered Upon Element Addition to DOM: JQuery Livequery Equivalent in Version 1.7

Is it possible to trigger an event when a certain element is added to a page, especially when I am using a Chrome extension and do not control the source page? I have explored the capabilities of JQuery 1.7's on() method, but it seems to focus on spe ...

Combining the Powers of Express.js and Kue.js

Currently, I am working on a personal project that involves processing tasks in the background. To achieve this, I need to establish communication between my Express and Kue frameworks. Here is a brief overview of my setup: My Express.js application forks ...

How can I retrieve the most recent date from a collection of hashes and then extract the corresponding name key/value pair?

I am dealing with an array of hashes structured like this: [ { "Address": 25, "AlertType": 1, "Area": "North", "MeasureDate": "2019-02-01T00:01:01.001Z", "MeasureValue": -1 }, { "Address": 26, "AlertType": 1, "Area": "West", "MeasureDa ...

Oops! It seems like there was an issue trying to access a property that doesn't exist (specifically, the

Encountering an error on the HomeScreen of my project I aim to manipulate the state of my HomeScreen Page using redux. The data is fetched from an API (an array of items) and then displayed on the screen. However, despite all these processes, an error me ...

The validation errors in the form of CodeIgniter are not being displayed by the JavaScript variable

Currently, I am utilizing the built-in validation_errors() function in CodeIgniter for my login form. The validation errors are displaying correctly in my view, but when I try to echo them into a JavaScript variable within the script to customize notificat ...

Using $eval in Angular to pass a string to an object

Here's the scenario: "var jsonData={first:{name:'John', age:30}};" I am looking to instantiate an object from this string, The standard JS eval function works perfectly for this purpose, however, when attempting to use $eval I encounter ...

What causes every item in the original list to change when using the list.append() method in Python?

I am trying to solve this coding problem: import json a = ''' { "c": { "d": [ { "e": "f" } ] } } ''' j = json.loads(a) l ...