[Vuejs]-Sort v-for List Alphabetically

3๐Ÿ‘

โœ…

If you want to sort all the songs by song, you can use computed property:

const app = Vue.createApp({
  data() {
    return {
      albums: [{id: "1", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1', keysavail:[{key: "Am", route2: "/"}]}, { song : 'check2.2' }]}, {id: "2", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "3", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "4", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 's' }, { song : 'c' }]}, {id: "5", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'b' }, { song : 'a' }]}, {id: "6", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "7", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "8", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "9", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "10", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "11", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "12", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "13", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]},{id: "14", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "15", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "16", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}, {id: "17", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : 'check2.1' }, { song : 'check2.2' }]}]
    }
  },
  computed: {
    sortedSongs() {
      const res =[]
      this.albums.forEach(a => a.songs.forEach(s => res.push(s)))
      return res.sort(function(a, b) {
        if(a.song < b.song) { return -1; }
        if(a.song > b.song) { return 1; }
        return 0;
      })
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="button" v-for="(item, i) in sortedSongs" :key="i">
    {{ item.song }}
  </div>
</div>

Leave a comment