Me7888
Me7888

Reputation: 1209

How to Filter Price range in JSON Data : Javascript or jQuery

I want to filter price range between 250 to 800 in JSON Data

My JSON Data :

var data = [{
    "name": "Lenovo Thinkpad 41A4298",
    "Price": 200
}, {
    "name": "Lenovo Thinkpad 41A2222",
    "Price": 200
}, {
    "name": "Lenovo Thinkpad 41Awww33",
    "Price": 6700
}, {
    "name": "Lenovo Thinkpad 41A424448",
    "Price": 600
}, {
    "name": "Lenovo Thinkpad 41A429rr8",
    "Price": 4200
}, {
    "name": "Lenovo Thinkpad 41A429ff8",
    "Price": 2200
}, {
    "name": "Lenovo Thinkpad 41A429ss8",
    "Price": 200
}, {
    "name": "Lenovo Thinkpad 41A429sg8",
    "Price": 500
}];

How to do in Javascript or jquery for Price range filter with All browser compatibility

I am try this code :

newdata=data.filter(function (el) {
return el.Price >= 250 &&
e1.Price <=800;
}); 

Upvotes: 0

Views: 12761

Answers (7)

Sachin Mewar
Sachin Mewar

Reputation: 513

You can filter values by using filter() method in array which will return a new filtered array.

const filteredValue = data.filter(items => {
      return items.Price >= 230 && items.Price <= 800
})

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

Working Demo

Use grep()

var t=$.grep(data,function(val,i){

   return val.Price >= 250 && val.Price <= 800;
});

Upvotes: 1

bobthedeveloper
bobthedeveloper

Reputation: 3783

You can make use of the filter method, which will create a new array with all the elements that passes the condition.

data.filter(function(x){ return x.Price >= 250 && x.Price <= 800});

If you want to use filter method in every browser you could add the polyfill method (see link) in your code.


Another option with basic javascript would be:

Looping trough the array with a simple for loop and test on the price range.

for(var i=0, length=data.length; i<length; i++){
   var current = data[i]; 
   if(current.Price >= 250 && current.Price <= 800){ 
      //INSERT CODE HERE 
   }
}

Upvotes: 5

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

you can do like this:

var filtered = new Array();
 $.each(data, function (index, item) {
    if(item.Price >= 250 || item.Price <=800)    
        filtered.push(item);
});
    console.log(filtered);

Working Fiddle

Upvotes: 1

Waldo Jeffers
Waldo Jeffers

Reputation: 2279

You can do the following :

var filteredData = data.filter(function(val,i,arr){
    return (val.Price >= 230) && (val.Price <= 800);
});

It uses a JavaScript Native function called filter.

Upvotes: 1

Artem Fitiskin
Artem Fitiskin

Reputation: 637

Try this solution:

data.filter(function(i, j) { 
    return (i.Price >= 250 && i.Price <= 800 ); 
});

Upvotes: 1

public override
public override

Reputation: 982

Just as you sad it, use .filter and shims for xbrowser. jQuery should have that functionality built-in.

var filtered = data.filter(filter_callback);
//

Upvotes: 1

Related Questions