Sort an array in Vue.js

前端 未结 5 801
时光取名叫无心
时光取名叫无心 2020-12-13 00:02

How can I sort an array by name or sex before displaying it in a v-for loop? https://jsfiddle.net/rg50h7hx/

5条回答
  •  抹茶落季
    2020-12-13 00:22

    Yes, an easy way to do this can be create a computed property which can return the sortedArray, like following:

    computed: {
      sortedArray: function() {
        function compare(a, b) {
          if (a.name < b.name)
            return -1;
          if (a.name > b.name)
            return 1;
          return 0;
        }
    
        return this.arrays.sort(compare);
      }
    }
    

    See working demo.

    You can find the documentation of sort here which takes a compareFunction.

    compareFunction Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

提交回复
热议问题