Vue sort function with correct data

I have a function that sorts user profile card by name, the problem is that it only switches the name but keeps the data of the other user in the card.

For example I had Max first with location Niagara and then Joe with location Melbourne, when I sort it put Joe first but with Niagara instead of Melbourne

<select name="sort" @change="sortArray"  v-model="filter">
<script>
props: { filter: '', selected:'name'},
data () {
    return {
      arrays: this.$store.state.arrays,
      }}
methods:{
sortArray: function() {if(this.filter === 'name')
   this.arrays.sort((a, b) => {return a.name < b.name ? -1 : 1})
  //this.componentKey += 1  //for data refresh
 }
}
</script>

I did a data refresh and that put the correct data but I’m looking for a way to correctly sort without having to refresh the data.
Thanks so much!

Instead of using a method try using a computed property to access this.array and then apply your sort before returning it.

I don’t think you should be using v-model=“filter” either. Pretty sure that will be mutating the filter prop which is something you should avoid in Vue. If you don’t need to pass filter in as a prop from outside the component I suggest moving it onto your data object where it can be mutated safely.

1 Like

Great solution, thanks so much!