Verify if a value is present in an array or falls within specified range of values

My goal is to input a value and determine if it exists in an array or falls within a specified range of values within the array. I then want to retrieve the index of the lower range value.

For instance, consider the following array:

dataArr = [10, 20, 30, 50, 70, 80, 90, 100];

If

input = 22;

The desired outcome is to find and return the index of the values 20 and 30 from dataArr.

Answer №1

let numArray = [10, 25, 30, 45, 60, 75, 80, 95];

function _locate(arr, target) {
  let indices = [],
      length = arr.length,
      j,
      idx = arr.indexOf(target);

  if (~idx) {
    return idx;
  }

  if (target < arr[0]) {
    return -1;  
  }

  for (j = 1; j < length; j++) {
    if (arr[j] >= target) {
      return [j - 1, j];
    }    
  }

  return -1;
}


console.log(_locate(numArray, 55));

DEMO: http://jsbin.com/xiqopo/1/

Ensure array is sorted before finding index

Answer №2

To accomplish this task, you can utilize a sorted array. The code snippet provided below demonstrates the solution.

 var inputValue = 22
 dataArr = sortThisArray(dataArr); //Sort the array if necessary
 for (var index=0; index<dataArr.size(); index++)
 {
      if(dataArr[index] > inputValue) //Check if the array value is greater than the input value
      {
          if(index < (dataArr.size()-1))
          {
               alert("The range is " + index + " and it's the last element in the array, so it's the higher index");
          }
          else //Identifying the LOWER BOUND index as index and HIGHER BOUND index as index+1
          {
              alert("The range is between " + index + " and " + (index+1));
          }
      }
 }

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

Set the scroll position to the top left corner (0,0) when a link to the current route is clicked or pressed

In my React application, I am faced with a challenge. When the user is on the route /gallery/images and clicks on a link (such as <a> or <Link> from react-router-dom) that leads to the same route currently being displayed, how can I detect thes ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

What is the best way to prevent using a function expression in order to return a local variable within an AngularJS factory?

Is there a way to return "stories" by setting "vm.stories = storyDataAsFactory.stories" instead of the current method "vm.stories = storyDataAsFactory.stories()" ? I've tried various combinations without any luck. Additionally, it seems that I can cal ...

State management at its core with integrated functionalities

I'm exploring different ways to manage application state within Angular 18 using its built-in features. Would it be effective to start with a simple service that utilizes dependency injection (DI)? As someone new to Angular 18, I'm a bit confuse ...

A guide on utilizing buttons within ion list items to execute actions independently for both the button and the list item

Currently, I have a list item with a button that is displayed based on a certain condition. My issue is that when I click the button, a popup should appear, but instead, it also navigates to the next page in the background. Can someone help me figure out h ...

What is the most efficient way to organize these arrays?

I've been racking my brain trying to figure out a sorting logic for some arrays, but I'm stumped. Maybe you have an idea? Imagine we have an array of objects structured like this: let obj = {day:'2', month:'6', year:'19 ...

During server and browser builds, NextJs encounters a 404 error when trying to access files named _ssgManifest.js and _buildManifest.js. Additionally, the file named _

I recently deployed a NextJs application on a digitalocean droplet running Ubuntu 22.04. "next": "12.2.3", "react": "18.2.0", Encountering a 404 error for the following files: _ssgManifest.js, _buildManifest.js, an ...

Angular model is not receiving the value of a false checkbox

One issue I am facing is with a form that includes a checkbox bound to an ng-model property. The problem arises when the checkbox is checked, as the value gets set in the model. However, when it is unchecked, the key and value remain unset, causing API val ...

Is there a way to download a file using an ajax request?

We are faced with a particular scenario in our application where: Client sends a request Server processes the request and generates a file Server sends the file back as a response Client's browser prompts a dialog for downloading the file Our appli ...

Guide to showing specific images alongside text through Ajax and Jquery

Currently, I am faced with the challenge of displaying specific text files using jQuery and Ajax. My goal is to have a text file appear based on the image being displayed. For instance, if an image of an apple is being shown, I would like the text below i ...

What is the method to restrict the selection of only one option for specific values in a multiple-selection dropdown menu?

Is there a way to create a dropdown menu with the following functionalities: I want to allow multiple selections for options A, B, and C, but disable multiple selection if option D is selected. Any tips on how to achieve this? Thank you. <label>Ch ...

Utilizing API data as props within an Autocomplete component in Reactjs with Material-UI

New to Reactjs, I am currently exploring the implementation of the Autocomplete component from material-ui. My goal is to pass the API link as a prop to the element. However, I'm stuck on how to pass the json label name as a prop to be used in "getOpt ...

React Redux Connect MapState not refreshing when filtering an item from a list

It seems like I may have misunderstood something or made a mistake when trying to subscribe to changes on a specific item within a collection in my store. My component isn't receiving updates unless I directly subscribe to the list. The following cod ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...

Watch as jQuery preloads every select list

There are two select lists, and the second one is dependent on the first. After loading the second list, I want to trigger some alerts. What is the most effective approach to accomplish this using jQuery? Let's say the second list is populated in the ...

File not found: The specified file 'C:Self Project eact-shopper eact-shopperclientuildindex.html' does not exist

I followed the tutorial and startup code by Reed Barger exactly, but every time I try to run the server I encounter this error: Error: ENOENT: no such file or directory, stat 'C:\Self Project\react-shopper\react-shopper\client&bso ...

Using JavaScript code to dynamically display the value of the variable MyProperty in HTML

Are there any limitations when using this construction in JavaScript? In my codeBehind, there is a property with intricate logic in the get method. It calls other methods and despite debugging showing a good value, it returns an empty string. I'm curi ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

Tips for generating multiple HTML hyperlinks using a for loop in a Chrome extension

function createDropDown(){ const tree = document.createDocumentFragment(); const link = document.createElement('a'); for(let index = 0; index < urlList.length; index++){ link.appendChild(document.createTextNode(urlList[index])); ...

The async/await feature is not pausing for the completion of the async.map function call

I'm encountering an issue in my Node.js app where I need to gather and format data using a helper function for an API endpoint. The problem arises when trying to loop through an array and make asynchronous calls to the database for each entry. Despite ...