How do i implement the functionality of a user filtering prices by entering min and max values in javascript?

gathagu Source

I am a newbie in programming and i would like to implement a filtering method where a user filters results based on a price range, i.e they should enter a min price and a max price and get a list of items within that price range.I am using javascript and angular 4 for my front end.



answered 6 months ago Tim Han #1

So you can just use a filter method to filter out the prices that fall in between min and max with this function:

function filterItems(items, min, max){
  return items.filter(item => item.price >= min && item.price <= max);

answered 6 months ago nsprenkle #2

You might try the Array.filter() method which returns values of an array which match some condition.

Assuming for example, you have an array of price values in a variable called values:

var values = [10, 20, 30, 40, 50],
  min = 15, max = 45;

var filteredValues = values.filter(function(value) {
  // Only keep values which are > min and < max
  return value > min && value < max;

// filteredValues will be [20, 30, 40]

There are fancier ways of writing this function but hope the plain syntax hopes to make it clear what's going on :)

Or, check out this example.

comments powered by Disqus