KIYA Daneshvarrad
KIYA Daneshvarrad

Reputation: 11

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

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>  

Upvotes: 1

Views: 60

Answers (2)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23490

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((a, b) => b - a)
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  {{ arraysorted }}
  {{myArray}}
</div>

Upvotes: 1

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27202

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>

Upvotes: 0

Related Questions