Home > database >  I have problem with sorting my array and I don`t know why
I have problem with sorting my array and I don`t know why

Time:09-14

my code have problem and I dont know why its not working and always give difrent erros I tried anyway the error: 'arraysorted' is not defined no-undef

 <div>
   {{ arraysorted }}
 </div>
</template>

<script>
const Array = [];
export default {
 data: () => ({
   Array: [1, 24, 23, 56, 76, 5, 468, 97, 65, 90, 23, 53, 23],
   arraysorted: [],
 }),
 mounted: {
   ArraySort() {
     return arraysorted = Array.sort(function (a, b) {
       return b - a;
     });
   },
 },
};
</script>  

CodePudding user response:

mounted() life cycle hook invoked once component mounted. Hence, Instead of writing a method in mounted, You can directly do the sorting and assign the results into arraysorted variable.

Live Demo :

new Vue({
  el: '#app',
  data: {
    Array: [1, 24, 23, 56, 76, 5, 468, 97, 65, 90, 23, 53, 23],
    arraysorted: []
  },
  mounted() {
    this.arraysorted = this.Array.sort((a, b) => b - a);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <pre>{{ arraysorted }}</pre>
</div>

CodePudding user response:

You can use computed property:

new Vue({
  el: "#demo",
  data: () => ({
   myArray: [1, 24, 23, 56, 76, 5, 468, 97, 65, 90, 23, 53, 23],
   
  }),
  computed: {
    arraysorted() {
      const arrSorted = [...this.myArray]
     return arrSorted.sort(function (a, b) {
       return b - a;
     });
   },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  {{ arraysorted }}
  {{myArray}}
</div>

  • Related