Using transform-items to order hits by date

81 views Asked by At

I'm working with an Algolia index that has a bunch of categories most of which we want to be ordered either alphabetically or randomised, but one category contains events and we want it to be sorted by date.

Currently we're using transform-items to randomise results and that works fine but it also randomises events so they're not in date order.

<ais-hits v-slot="{ items }" :transform-items="transformItems">

transformItems(items) {
    if (this.isEventsActive) { // this will detect when the events category has been selected
        // what goes here
    } else {
        for (
            let j, x, i = items.length;
            i;
            j = Math.floor(Math.random() * i), x = items[--i], items[i] = items[j], items[j] = x
        );
        return items;
    }
},

So if I have a date field product_event what do I need to do to sort by that in transformItems?

1

There are 1 answers

0
Tyssen On

This is what I needed:

function sortByDate(a, b) {
  if (a.product_event < b.product_event) {
    return -1;
  }
  if (a.product_event > b.product_event) {
    return 1;
  }
  return 0;
}
return items.sort(sortByDate);