Matt B
Matt B

Reputation: 57

Re-ordering the index on a computed array?

I've searched through the docs and questions online but can't find out how to modify the index order of my computed array. Any idea on where to start?

I have an array of 'offers' objects that I would like to order by 'offer.price.from' in the typical ascending or descending select box.

  <!-- SORT BY SELECT --> 
 <select v-model="sortby" >
 <option value="ascending"> Sort: Price ascending</option>
 <option value="descending"> Sort: Price descending</option>
 </select>

<div v-for="offer in filteredOffers" class="grid-4 item hotel hotel-item"> 
<!-- OFFER CONTENT HERE --> 
</div>

computed: {
filteredOffers () {
return this.offers.filter(offer => {
    return (offer.island === this.filters.islandFilter || this.filters.islandFilter === 'All') // Island 
      && (offer.starrating === this.filters.starRating || this.filters.starRating === 'All') // Star Rating 
      && (offer.board === this.filters.boardBasis || this.filters.boardBasis === 'All') // Board Basis
      && (offer.duration === this.filters.duration || this.filters.duration === 'All') // Duration 
      && (offer.price.from < this.filters.price) // Price
      && (this.filters.travelby === 'sea' && offer.travel.air === false || this.filters.travelby === 'All') // Sea or Air
   // && (this.filters.range.startDate >= offer.dates.start && offer.dates.end <= this.filters.range.endDate)
   });
  }
  }

Upvotes: 0

Views: 53

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Try this by sorting the filtered array and returning it as a computed property based on sortby data item :

computed: {
  filteredOffers() {
    let filtered = this.offers.filter(offer => {
      return (offer.island === this.filters.islandFilter || this.filters.islandFilter === 'All') // Island 
        &&
        (offer.starrating === this.filters.starRating || this.filters.starRating === 'All') // Star Rating 
        &&
        (offer.board === this.filters.boardBasis || this.filters.boardBasis === 'All') // Board Basis
        &&
        (offer.duration === this.filters.duration || this.filters.duration === 'All') // Duration 
        &&
        (offer.price.from < this.filters.price) // Price
        &&
        (this.filters.travelby === 'sea' && offer.travel.air === false || this.filters.travelby === 'All') // Sea or Air
      // && (this.filters.range.startDate >= offer.dates.start && offer.dates.end <= this.filters.range.endDate)
    });

    if (this.sortby == 'ascending') {
      return filtered.sort((a, b) => {
        return a.price.form - b.price.form;
      })
    } else {
      return filtered.sort((a, b) => {
        return b.price.form - a.price.form;
      })
    }
  }
}

Upvotes: 2

Related Questions