Obtain a series of numbers from the arranged array

Consider a sorted array containing numbers, for instance:

const array = [100, 400, 700, 1000, 1300, 1600]

We have a function that requires two arguments as input:

function foobar(min, max) {}

The task of this function is to retrieve the numbers from the array, starting from the first value that is >= to the min and ending with the last value that is >= to the max.

foobar(250, 1010) // returns [400, 700, 1000, 1300]
foobar(0, 15) // returns [100]

How can we achieve this using modern JavaScript?


array.filter((num) => {
  return num >= min && num <= max
})

This solution always excludes the last number. 🤔

Answer â„–1

This code snippet showcases the efficiency of using a for...of loop.

const numbers = [100, 400, 700, 1000, 1300, 1600];

function filterNumbers(arr, min, max) {
    let result = [];
    for (let num of arr) {
        if(min <= num && num <= max) {
            result.push(num);
        } else if(num > max) {
            result.push(num);
            break;
        }
    }
    return result;
}

console.log(filterNumbers(numbers, 0, 15));     // outputs [100]
console.log(filterNumbers(numbers, 250, 1010)); // outputs [400, 700, 1000, 1300]

This approach is straightforward, adheres to traditional programming principles, and iterates through the array efficiently in a single pass.

Answer â„–2

Let's explore a solution

const numbers = [100, 400, 700, 1000, 1300, 1600];

const filterNumbers = (minValue, maxValue) => {

    const lowestHigherNumber = numbers.find(num => (num >= maxValue));
    
    const isWithinRange = value => (value >= minValue && value <= lowestHigherNumber);
    return numbers.filter(isWithinRange);
};

console.log( filterNumbers(0, 150) );
console.log( filterNumbers(400, 1500) );

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

Steps to transfer an array from an HTML page to Node.js and subsequently save it in a database

Looking for guidance on how to transfer a JavaScript array using Node.js to MySql. Seeking helpful videos or explanations to clarify the process. Thank you! ...

Navigational inconsistency with SVG icons integrated into Bootstrap Navbar

Bootstrap offers icons in embedded SVG format. These SVG tags can be directly added to HTML code. However, when I included the SVG tag in my navbar, the icon did not appear centered even after using the vertical-align: middle CSS property. The icon did not ...

Notifications will be displayed with Alertifyjs to the individual who activated them

Just diving into the world of nodejs and express framework, so I appreciate your patience as I navigate through this learning process. I've implemented the alertifyjs library to display notifications for different alerts on my site. However, I&apos ...

Instructions on how to showcase a standard text within a designated text container

I am currently facing an issue with a textarea or textbox that is dynamically receiving URLs from a database. The textbox is displaying the full URL address, which is not visually appealing. I would like to replace this with some generic text such as "cl ...

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div? I have put together a DEMO on codepen.io In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of ...

javascript unusual comparison between strings

I am working on an ajax function that is responsible for sending emails and receiving responses from the server in a JSON format with type being either success or error. $("#submit_btn").click(function(event) { event.preventDefault(); var post_d ...

Best practice for structuring an object with multiple lengthy string elements in the GCP Datastore Node Library

My JavaScript object is structured like this: const data = { title: "short string", descriptions: [ "Really long string...", "Really long string..." ] } I need to exclude the long strings from the indexes, but I ...

php split not functioning in javascript template

I have come across some previous discussions on the same topic. Below are the links to those posts: Javascript Template Engine Use with jQuery What is x-tmpl? I am attempting to integrate a php explode function into a javascript template. The plugin I ...

Utilizing ID's within a jade template embedded within a P HTML element

Using the jade template, I successfully formed this paragraph. My next step is to add an ID or a class around the word stackoverflow. How can I achieve this in jade? I am aware that in regular HTML we would use something like <div class="className"> ...

javascript image alert

I want to upgrade a basic javascript alert to make it look more visually appealing. Currently, the alert is generated using if(isset($_GET['return'])) { // get a random item $sql = "SELECT * FROM pp_undergroundItems AS u LEFT JO ...

Obtain the existing text from the <select runat="server"> element

Similar Question: Retrieve Text Selection with Runat=“Server” 1: HTML <div id="dialog"> <select id="Select1"> <option>1</option> <option>2</option> <option>3 ...

What is the location where nvm saves its node.js installations?

I'm having trouble locating where node.js installations are stored after downloading and installing through commands like: nvm install 5.0 Can anyone provide some insight on this? ...

What steps can I take to incorporate mathematical functions into my HTML webpage?

Are you facing a similar challenge on your blog? I'm looking for a way to allow users to include math formulas using Latex syntax in their comments without making server adjustments. My only option is to embed a script in the HTML page. Any suggestion ...

Why does the hashtag keep popping up every time I launch the Bootstrap Modal?

I can't figure out why this keeps happening. I researched how to eliminate hashtags from the URL and found multiple solutions. However, none of them proved to be helpful as they only removed the hashtag, requiring a page refresh which still didn' ...

Is it possible to create a numerical unique identifier? What is the best way to resolve the issue of duplicate IDs safely?

I have a question regarding an old code that manually generates a random ID as a number, which has recently led to a duplicate ID issue. What is the most secure and effective solution to address this problem? I am considering using UUID to generate an ID, ...

Create a hover effect on HTML map area using CSS

Is it possible to change the background color of an image map area on hover and click without using any third-party plugins? I attempted the following code: $(document).on('click', '.states', function(){ $(this).css("backgro ...

An easy guide to rerouting a 404 path back to the Home page using Vue Router in Vue.js 3

Hello amazing community! I'm facing a small challenge with Vue.js 3. I am having trouble setting up a redirect for any unknown route to "/" in the router. const routes = [ { path: "/", name: "Home", component: Home, }, { path: "* ...

What is the best way to trigger a JavaScript alert from a static method in Asp.net server-side code?

I am struggling to have a JavaScript alert work in a static method for server-side code in ASP.NET using C#. I've attempted multiple approaches, but nothing seems to be effective. One example is as follows [WebMethod] public static void EntrySave(st ...