[Vuejs]-Vue sort object key values descending by english string number

0👍

What you try to achieve is sorting an object structure in a descending order, by key, which is a numeric value of the equivalent word.

First, you should probably find a library which converts textual words to numbers. In the bellow example, I have chosen words-to-numbers.

Then, you have to sort each [key, value] pairs of your object, depending on the numeric value you get from the word conversion.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <option v-for="[key, item] in orderedData" :value="key" v-bind:key="key">
    <span v-html="item"></span>
  </option>
</div>
import wordsToNumbers from 'words-to-numbers';

new Vue({
  el: '#app',

  data: {
    data: {
      One: "One",
      Three: "Three",
      Five: "Five"
    }
  },

  computed: {
    orderedData() {
      return Object.entries(this.data).sort((a, b) => {
        return  wordsToNumbers(b[0].toLowerCase()) - wordsToNumbers(a[0].toLowerCase())
      })
    }
  }
})

Leave a comment