Search code examples
javascriptvue.jssorting

How can I sort using v-for in vuejs


How can I sort using data?

I want to sort in my data using

-start_at -end_at

for example;

data: [
  {
    start_at: '08:00',
    end_at: '09:00',
  },
  {
    start_at: '07:00',
    end_at: '08:00',
  },
  {
    start_at: '06:00',
    end_at: '07:00',
  },
...
],

How can I sort this data from lowest start time (ie 06:00 will be first) to highest?

Thank you guysss !!


Solution

  • use computed property

    <template>
      ...
      <div v-for="time in sortedTime">
      </div>
      ...
    </template>
    
    <script>
    export default {
      data() {
        return {
          time: [],
        }
      },
    
      computed: {
        sortedTime() {
          return [...this.time].sort((a,b) => ...)
        }
      }
    }
    </script>
    
    

    Docs: https://v2.vuejs.org/v2/guide/computed.html#Basic-Example