Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario:

let rangeOfInterest = [25 , 44];
let input = [10, 20, 30, 40, 50, 60];

I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the input values completely, for example [85, 95] or [0, 100].

output1 = [30, 40];

If there are values adjacent to this output, I also want to include them;

finalOutput = [20, 30, 40, 50];

Currently, I achieve this by filtering the array and identifying the indexes of the first and last elements in the result to extract additional samples if needed. Is there a more concise approach without using approximately 20 lines of code?

Note: The sample values will be floating-point numbers, but integers are used in this simplified example.

Answer №1

To identify the index of the first element greater than the minimum range and the index of the initial element larger than the maximum range, slice based on these indexes (minIndex - 1, maxIndex + 1).

const findRange = ([min, max], numbers) => {
  const startIdx = numbers.findIndex(num => num > min);
  const endIdx = numbers.findIndex(num => num > max);
    
  return numbers.slice(
    startIdx > 1 ? startIdx - 1 : 0,
    endIdx === -1 ? numbers.length : endIdx + 1
  );
};


const data = [10, 20, 30, 40, 50, 60];

console.log(findRange([25 , 44], data));

console.log(findRange([25 , 65], data));

console.log(findRange([-25 , 65], data));

Answer №2

Give this a shot:

let data = [10, 20, 30, 40, 50, 60];
let range = [25 , 44];

let selectedValues = data.filter(function(value) {
  return Math.min(...range) <= value && Math.max(...range) >= value;
});

selectedValues.push( Math.floor(Math.min(...range) / 10) * 10 ); //adding 20
selectedValues.push( Math.floor(Math.max(...range) / 10) * 10 ); // adding 40

console.log(selectedValues)

Answer №3

let roiValues = [25 , 44]; //adjusting range of interest variable name
    let numbersArray = [10, 20, 30, 40, 50, 60];
    function checkInRange(value1, value2){//assuming value1<value2 always
    return (number)=>{
         return number>=value1 && number<=value2;
       }
    }
    let startIndex=0;
    let endIndex=0;
    var filteredArray = numbersArray.filter((value, index) => {
           let isMatched = checkInRange(roiValues[0],roiValues[1])(value);
           if(!startIndex){
              startIndex=isMatched?index:0;
           }
           endIndex = isMatched&&(index>endIndex)?index:endIndex;
           return isMatched;
           });
    endIndex<numbersArray.length?filteredArray.push(numbersArray[endIndex+1]):'';
    startIndex>0?filteredArray.splice(0,0,numbersArray[startIndex-1]):'';
    console.log(filteredArray);

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

Cannot assign border to an undefined element - JavaScript

Currently, I am attempting to validate some code using javascript. However, I am encountering a frustrating issue where I keep getting an "Uncaught TypeError: Cannot set property 'border' of undefined". Being relatively new to javascript, I ...

The client continues to request the file through the REST API

I have noticed a behavior with an audio file stored on the server that clients can request via a REST API. It seems that every time the audio is played again, a new request is sent to the server for the file. Is there a way to prevent this or cache the dat ...

What is causing the array elements to be iterated through multiple times?

My goal is to display all the titles from an array called 'title element' containing 10 values. However, I am encountering a problem: The for loop outputs all 10 values repeatedly 10 times. The titles are: Title 1, Title 2, Title 3, Title 4, T ...

A Guide to Making a Floating Widget That Can Move Beyond the Boundaries of a Website in React

Currently, I am in the process of developing a project that requires the implementation of a floating widget capable of overlaying content not just within the confines of the website, but outside as well. This widget needs to have the ability to remain on ...

How to trigger a function when clicking on a TableRow in React using MaterialUI

Can someone help me understand how to add an onClick listener to my TableRow in React? I noticed that simply giving an onClick prop like this seemed to work: <TableRow onClick = {()=> console.log("clicked")}> <TableCell> Content </Ta ...

Differences Between Pointers for int and char Arrays in C

I see that there have been similar inquiries before, however, this one pertains specifically to arrays. Here is an example of what I can do: char *names[] = { "John", "Paul", "George", "Ringo" }; and then: printf("%s\n", names[0]); But why doesn& ...

Running a Jest test that triggers process.exit within an eternal setInterval loop with a latency of 0, all while utilizing Single

In the original project, there is a class that performs long-running tasks in separate processes on servers. These processes occasionally receive 'SIGINT' signals to stop, and I need to persist the state when this happens. To achieve this, I wrap ...

Chrome Extension for Extracting Data from Websites

I am in the process of developing my Google Chrome extension that needs to store a variable from another website by passing it over. Below is the snippet of code found in the script.js file of the website: var editorExtensionId = "extension"; & ...

What is the reason behind VueJS animations only functioning in a single direction?

I'm completely baffled by this issue. It seems that Vue3 is able to apply the move animation class correctly for a <transition-group/> when there is a list of items, but this only happens if the list is moved forward. I've created a CodePen ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...

Delete ObjectId from Array using Node and Mongoose

Currently, I am working on a website that features a comments section for campsites. This platform is similar to Yelp but focuses on reviewing campsites. Each campsite in the MongoDB collection has a field called "comments" which stores the IDs of all comm ...

Sorting custom strings in Javascript with special characters like dash (-) and underscore (_)

I am attempting to create a custom sorting method with the following order: special character ( - first, _ last) digit alphabets For instance, when sorting the array below var words = ['MBC-PEP-1', 'MBC-PEP01', 'MBC-PEP91&apo ...

Changing the fill color of an SVG pattern remains unchanged

I have been working with Vue.js to create SVGs with shape patterns as background. The patterns themselves are functioning correctly, but I am encountering an issue when attempting to dynamically change the color of the pattern filling by passing props. D ...

Sending an array from JavaScript to PHP and then back to JavaScript

I have a task to transfer an array from one webpage to a PHP page for it to be saved in a file, and then another webpage has to retrieve that array from the file. Currently, I have an array in JavaScript containing all the necessary information: JavaScri ...

Automatically selecting checkboxes from an array using ReactJS

Hello there, I am a beginner working with react and I could really use some help with the issue below. Can you assist me? I am trying to figure out how to populate or check/uncheck checkboxes based on an Array's result. Specifically, I want to have ...

Asynchronous and nested onSnapshot function in Firestore with await and async functionality

I'm facing an issue with the onSnapshot method. It seems to not await for the second onsnapshot call, resulting in an incorrect returned value. The users fetched in the second onsnapshot call are displayed later in the console log after the value has ...

Error encountered with select2 when using a remote JSONP dataset

When attempting to query the Geonames data using select2, everything seems to work fine with formatting the results. However, an error occurs once the results are populated, which I suspect is preventing the formatSelection function from running properly. ...

Instructions for incorporating a TypeScript type into a Prisma model

I am trying to incorporate a Type Board into one of my Prisma models. However, I am encountering an error stating that "Type 'Board' is neither a built-in type, nor refers to another model, custom type, or enum." Can someone provide guidance on h ...