[Vuejs]-VueJS – Sorting array of objects coming from the API response

1👍

You could create a computed property on your component that sorts the array, and then iterate over that:

created() {
    this.fetchAutomobiles();
},
computed: {
    automobilesSorted() {
        return this.automobiles.sort((a, b) => {
            return a.name.localeCompare(b.name);
        });
    }
},
data() {
    return {
        automobiles: []
    };
},
methods: {
    fetchAutomobiles() {
        this.$http.get('/automobiles').then((response) => {
            this.automobiles = response.data;
        });
    }
}
<div class="vx-col" v-for="automobile in automobilesSorted" v-bind:key="automobile.id">
    <!-- -->
</div>

1👍

What you need to do is sort the array by its property after it is received.

For example if you want to sort by automobile’s name, you can do this:

created () {
  this.$http.get('/automobiles')
    .then((response) => { 
       this.automobiles = response.data.sort((a, b) => a.name - b.name); 
    })
}

Leave a comment