Sorting by multiple properties, depending filters

Hi there,

imagine a simple entity like // simple entity const Item = Ember.Object.extend({ name: null, color: null, price: null });

and a model hook like model() { return { items: [ Item.create({ name: 'Apple', color: 'red', price: 2 }), Item.create({ name: 'Orange', color: 'red', price: 3 }), Item.create({ name: 'Pear', color: 'yellow', price: 2 }), Item.create({ name: 'Grapes', color: 'green', price: 3 }), Item.create({ name: 'Banana', color: 'yellow', price: 2 }), Item.create({ name: 'Melon', color: 'green', price: 5 }), Item.create({ name: 'Strawberries', color: 'red', price: 7 }), Item.create({ name: 'Porsche 911 Cabrio S', color: 'silver', price: 20 }), Item.create({ name: 'FoldableBucket', color: 'black', price: 8 }) ] } },

What is the best way to implement depending filter controls in the controller e.g. a list of checkboxes with colors and a range slider for prices. So that checking just ‘green’ and ‘red’ shrinks the price range slider from 2 to 7 and vice versa…

Thanks in advance, Martin

This isn’t necessarily elegant, but if it were me I’d just do something like:

// app/controllers/<name>.js
  ...
  filtered: Ember.computed.filter('model', function(item, index, array) {
    // filter by colors
    return this.get('colors').indexOf(item.get('color')) > -1;
  }),
  filteredPrices: Ember.computed.mapBy('filtered', 'price'),
  minPrice: Ember.computed.min('filteredPrices'),
  maxPrice: Ember.computed.max('filteredPrices'),
  ...

So you could use ‘minPrice’ and ‘maxPrice’ as the range of your slider, and filtered as the list of filtered items.

2 Likes

Looks good to me! Which includes ‘elegant’ as well… Thank you!