vue配列ソート、オブジェクトソート

934 ワード


  

{{sortAry}}

{{sortStudents}}

export default {
  data() {
    return {
      ary: [22, 42, 11, 32, 12, 54, 2, 3],
      students: [
        { name: 'GoldSunny', age: 18 },
        { name: 'Hong', age: 30 },
        { name: 'Apple', age: 21 },
        { name: 'King', age: 45 }
      ]
    }
  },
  computed: {
    sortAry: function () {
      return this.ary.sort(sortNum)
    },
    sortStudents: function () {
      return sortBykey(this.students, 'age')
    }
  }
}
function sortNum(a, b) {
  return a - b
}
function sortBykey(ary, key) {
  return ary.sort(function (a, b) {
    let x = a[key]
    let y = b[key]
    return ((x < y) ? -1 : (x > y) ? 1 : 0)
  })
}