Utilize JavaScript to filter an array and extract a subset based on two specified range parameters

How can I extract a subset from an array that overlaps with two specified ranges?

Let's say we have an array filled with objects:

const list = [{
    id: 1,
    price: "10",
    weight: "19.45"
  },{
    id: 2,
    price: "14",
    weight: "27.8"
  },{
    id: 3,
    price: "45",
    weight: "65.7"
  },{
    id: 4,
    price: "37",
    weight: "120.5"
  },{
    id: 5,
    price: "65",
    weight: "26.9"
  },{
    id: 6,
    price: "120",
    weight: "19.3"
  },{
    id: 7,
    price: "20",
    weight: "45.7"
  }]

We want to filter this array based on specific ranges defined for two parameters price and weight.

let range = {
    startPrice: 15,
    endPrice: 60,
    startWeight: 22.0,
    endWeight: 70.5,
  }

The goal is to get a new array with objects that fall within both of these specified ranges. The expected result should be:

filtered = [{
    id: 3,
    price: "45",
    weight: "65.7"
  },{
    id: 7,
    price: "20",
    weight: "45.7"
  }]

Objects with id: 3 and id: 5 meet the criteria for both ranges. How should the list.filter() function be implemented in this case? Any assistance would be highly appreciated. Thank you.

Answer №1

Note: I have utilized the parseFloat function to convert values from a String format to a numeric format. There are alternative methods available to achieve the same conversion from a String to a Number.

var list = [{"id":1,"price":"10","weight":"19.45"},{"id":2,"price":"14","weight":"27.8"},{"id":3,"price":"45","weight":"65.7"},{"id":4,"price":"37","weight":"120.5"},{"id":5,"price":"65","weight":"26.9"},{"id":6,"price":"120","weight":"19.3"},{"id":7,"price":"20","weight":"45.7"}];
var range = {
  startPrice: 15,
  endPrice: 60,
  startWeight: 22.0,
  endWeight: 70.5
};

var filtered=list.filter(
  element=> {
    var elementprice=parseFloat(element.price);
    var elementweight=parseFloat(element.weight);
    if(
      elementprice>=range.startPrice &&
      elementprice<=range.endPrice &&
      elementweight>=range.startWeight &&
      elementweight<=range.endWeight
    ) {
      return true;
    }
    return false;
  }
);
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Saying you mean 3 and 7

Furthermore, it is necessary to eliminate the quotes or convert to a number. Keep in mind that a filter requires a true or false for a Boolean test, without the need for an if statement.

const list = [{ id: 1, price: "10", weight: "19.45" }, { id: 2, price: "14", weight: "27.8" }, { id: 3, price: "45", weight: "65.7" }, { id: 4, price: "37", weight: "120.5" }, { id: 5, price: "65", weight: "26.9" }, { id: 6, price: "120", weight: "19.3" }, { id: 7, price: "20", weight: "45.7" }];
 let range = { startPrice: 15, endPrice: 60, startWeight: 22.0, endWeight: 70.5, }

const res = list.filter(item => 
  +item.price >= range.startPrice && 
  +item.price <= range.endPrice &&
  +item.weight >= range.startWeight &&  
  +item.weight <= range.endWeight);
console.log(res);

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

Exploring the source of the "Unexpected token ;" issue in an Express-JS application

Working on a project with Parse and Express-JS, I encountered an issue when trying to display an EJS page. The error message Unexpected token ; appeared while running the command line parse develop MyApp in Terminal. Below is the full stack trace of the er ...

Tips for triggering a child component function during parent events:

Scenario Vue 2.0 documentation and various sources such as this one emphasize that communication from parent to child components is done through props. Inquiry How can a parent component inform its child component that an event has occurred using props? ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

What makes this CSS causing render blocking?

I've been meticulously following the Google PageSpeed guidelines in order to optimize the performance of my website. Upon running an analysis, Google provides me with a score based on their set guidelines. There's one particular guideline that ...

Determine the date 7 days before today using JavaScript

I've been trying to calculate the date that is 12 days before today's date, but I'm running into an issue where it's not returning the correct result. For instance, if today is November 11, 2013 (mm/dd/yyyy), the code returns October 30 ...

Employ the find() function to ascertain the result of a condition

I'm struggling to grasp how to utilize the find() method in a conditional statement. In simple terms, I want the conditional to evaluate as true if the value of item.label is equal to the value of e.target.value. if (this.props.Items.find(item => ...

Update the react component's state props to trigger a re-render when the state changes

I'm facing an issue with getting a component to rerender in React even though one of its components is a piece of state that receives updates. The piece of state in question is 'board': const [board, setBoard] = useState("") The component i ...

How can Vue JS be used to assign numbers to specific elements in an array that meet certain conditions?

Imagine having an array of objects within your Vue state like the following: [ {name: "Daniel", default: false}, {name: "Ross", default: true}, {name: "Rachel", default: false}, {name: "Joey", default: false} {n ...

Passing a JavaScript variable through a URL link

I need to pass a JavaScript variable to a specific webpage. Here is the code I am using: <script> function hello() { var data="hello"; <a href="www.mytestsite.com?var="' +data +'>Send now</a> } </script> The hello() func ...

Removing Firefox's button outline when the mouse is pressed, not clicked, hovered over, or focused

Is there a way to remove the default outline that appears on my Bootstrap page button when it is pressed and not released? I have already tried targeting mouse focus and active states, but haven't been successful. Default Button https://i.sstatic.ne ...

The Next.js application is functioning smoothly in development, but encounters errors during the building and deployment processes

While my Next.js app compiles and runs smoothly locally during development (using npm run dev), I encounter a failed build when attempting to compile the project (using npm run build). After researching online, it seems that unhandled promises may be the c ...

What is the best way to implement conditional hook usage in React?

Having two hooks at my disposal, useLocalStorage and useQuery, I find myself wondering about conditionally utilizing one of them based on an input prop. I'm considering writing the following: const [value, setValue] = localStorage ? useLocalStorage() ...

Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site. return this.getFields() .reduce((mappings, field) =& ...

An undefined value error occurred while attempting to save data to a MongoDB collection through a node/express server

Anticipated Outcome I am looking to successfully save a new page to mongo db after server validation of input, without encountering any errors in the console. The issue seems to be originating from the post method in the routes in admin_pages.js and I&apos ...

PHP script only inserting the first element of an array into the MySQL database table

When attempting to capture up to 15 entries upon submission, the code provided is only capturing the initial entry in the database. Additionally, an error message is being displayed, stating: An error in the SQL syntax has occurred. Ensure to refer to the ...

I am puzzled as to why my text and div boxes are displaying in my navbar/hamburger menu instead of at the bottom of the page

Greetings, everyone! This is my debut post here so bear with me if it's not presented in the correct format. Currently, I am deep into creating a website using HTML, CSS, and just a hint of JavaScript. My primary focus right now is on building the ho ...

Exploring characteristics using DocumentTraversal

My goal is to list out the attributes of elements using DocumentTraversal specifically for IE11. While I have been successful in enumerating element attributes, I am facing an issue when trying to do the same with attributes. The enumeration stops at the f ...

Firmidable with Node.js

I am a beginner in the world of node.js and I have been soaking up knowledge from various resources like bootcamps and websites. My current challenge is with uploading a file using the formidable module within the node.js and express.js framework. Whenever ...

Link the asp control as you input text into the Text box

I currently have a situation where I am working with a text box and a repeater control. My goal is to dynamically bind the data to the repeater control as the user types into the text box, without requiring them to press the enter key or click with the mou ...

Combining elements of an array using the merge() function within a while() loop and then extracting those values in array format using $row['field_name']

My query is being processed here. The $merge variable holds the specific structure I require. I aim to convert the $merge data into an array and extract each value as $row[0], $row[1], $row[3], etc... outside of the while loop. while ($row = mysql_fetch_ ...