Iterate an object with reverse sorted keys Iterate an object with reverse sorted keys vue.js vue.js

Iterate an object with reverse sorted keys


You can created a computed property that sorts your object keys in descending order:

sortedGroupKeys() {     return Object.keys( group ).sort( ( a , b ) => b - a); }

then you can loop though it.

<WordsTable     v-for="(key in sortedGroupKeys)"    :words="group[ key ]"    :word-length="key"/>

Hope this helps.


This should work. Iterate over a sorted list of the keys.

console.clear()Vue.component("WordsTable",{  props: ["words", "length"],  template: `    <table>      <caption>Words of length {{length}}</caption>      <tbody>        <tr v-for="word in words"><td>{{word}}</td></tr>      </tbody>    </table>    `})new Vue({  el: "#app",  data:{    words: [      "hello", "apple", "mister", "wut", "phenomenal", "and", "vue", "four", "word"    ]  },  computed:{    grouped() {      return this.words.reduce((groups, word) => {        (groups[word.length] = groups[word.length] || []).push(word)        return groups      }, {})    },    sortedDesc(){      return Object.keys(this.grouped).sort((a,b) => b - a)    }  }})
caption { text-align: left; border-bottom: 1px solid black;}table {  width: 10em;  margin-bottom: 1em;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script><div id="app">  <words-table v-for="length in sortedDesc" :key="length" :words="grouped[length]" :length="length"></words-table></div>