Y
Y
YakovSpb2020-02-11 16:16:28
Vue.js
YakovSpb, 2020-02-11 16:16:28

How in Vue to sort an array alphabetically by a certain property if a certain checkbox is true?

<div v-else class="app-content">
        <div class="items">
          <div 
          v-for="(dog, idx) in allDogs" 
          :key="idx"
          class="card"
          >
          <img :src="dog.url" alt="alt">
          <div class="card__name">{{dog.breeds[0].name}}</div>
        </div>
      </div>

    </div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-02-11
@YakovSpb

Make a computed property that, depending on the state of the checkbox, will represent the array in default or alphabetical order:

<input type="checkbox" v-model="sort">
<div v-for="dog in sortedDogs">

data: () => ({
  sort: false,
}),
computed: {
  sortedDogs() {
    return this.sort
      ? [...this.allDogs].sort((a, b) => a.breeds[0].name.localeCompare(b.breeds[0].name))
      : this.allDogs;
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question