Home » vue » Sort a list in vuejs

Sort a list in vuejs

Posted by: admin November 26, 2021 Leave a comment

Questions:

I receive an array of sport events like that in a component :

[{ ligue: "champions league", event: "psg - varsovia", scoreteam1: 1, scoreteam:2},{ ligue: "world cup", event: "belgium - england", scoreteam1: 1, scoreteam:2},{ ligue: "champions league", event: "madrid - fc bruge", scoreteam1: 3, scoreteam:2},{ ligue: "champions league", event: "milan - dortmund", scoreteam1: 1, scoreteam:2},{ ligue: "world cup", event: "japan - danemark", scoreteam1: 1, scoreteam:5}]

And i would like to get a list of all events for the “ligue” like that:

Champions league:
*psg – varsovia
*madrid – fc bruge
*milan – dortmund

World cup:
*belgium – england
*japan – danemark

for now i loop over my soccerlist like that so each time i repeat the name of the “ligue”:

<section v-for="(loop,i) in soccerlist" :key="i" ><header>  {{ loop.ligue }}</header><div> {{loop.event}} {{ loop.scoreteam1 }} {{ loop.scoreteam2 }}</section>

so i want to have all matches from a “ligue”, how can i do that with vue js ?

Answers:

You’re probably better off using a computed property to sort your array into leagues. For example:

computed: {
  sortedGames() {
    return this.soccerlist.reduce((acc, game) => {
      if (acc[game.ligue]) acc[game.ligue].push(game);
      else acc[game.ligue] = [game];
      return acc;
    }, {})
  }
}

This will return you an object, with each game grouped by ligue. You can then v-for="ligue in sortedGames" and go from there.