0

How to arrange data (comments) based on which has the most votes using vue.js? Thanks.

data: {
    comments: [{
        title: "Great article!",
        votes: 5
    }, {
        title: "VueJs commenting system with votes!",
        votes: 5
    }, {
        title: "The random pun that gets a lot of upvotes",
        votes: 85
    }]
}
Chirag Ravindra
  • 4,760
  • 1
  • 24
  • 35
Stefan
  • 1
  • 1
  • 1
    Hello. Welcome to StackOverflow. Please share what you have tried already and try to show samples of the data structures involved. I would suggest you take a look at the [How to Ask Guide](https://stackoverflow.com/help/how-to-ask) and edit your question to have better context for people trying to help and others having the same question. Thanks. – Chirag Ravindra Apr 04 '18 at 08:22
  • 1
    Sure thing! Thank you. – Stefan Apr 04 '18 at 08:28
  • 4
    Possible duplicate of [Sorting an array of JavaScript objects](https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Lassi Uosukainen Apr 04 '18 at 08:30

1 Answers1

2

You could check the Vue documentation itself, where your use case is properly described. See here.

Basically you have to:

1 - define a computed property performing the sorting, for example:

computed: {
    sortedComments: function () {
      return this.comments.sort((a, b) => parseInt(a.votes) - parseInt(b.votes));
    }
}

2 - iterate over the computed property:

<li v-for="n in sortedComments">{{ n }}</li>
tony19
  • 125,647
  • 18
  • 229
  • 307
P3trur0
  • 3,155
  • 1
  • 13
  • 27