How to sort an array of objects form

Directly to the first method:

     sortByKey:function(arr,key){
        return arr.sort(function(a,b){
          var x = a[key];
          var y = b[key];
          return ((x<y) ? -1 : ((x>y) ? 1 : 0))
        })
      }  

    Here I was vue used in the project, in fact, what projects can all be so used

structure:

    <ul>
      <li v-for="child in child" >{{child.name}}-{{child.age}}</li>
    </ul>

  Initial data:

    data() {
      return {
        childes:[
          {
            name:"a",
            age:25
          },
          {
            name:"b",
            age:20
          },
          {
            name:"c",
            age:15
          },
          {
            name:"d",
            age:5
          }
        ]
      }
    },

  result:

 

Requirements by age from small to big Sort:

methods methods:

    methods:{
      sortByKey:function(arr,key){
        return arr.sort(function(a,b){
          var x = a[key];
          var y = b[key];
          return ((x<y) ? -1 : ((x>y) ? 1 : 0))
        })
      }
    }

  computed algorithms:

     newChild:function(){
        return this.sortByKey(this.childes,'age')
      }

  Note that the main loop to get rid then circulation is newChild, namely:

    <ul>
      <li v-for="child in newChild" >{{child.name}}-{{child.age}}</li>
    </ul>

  The result is:

 

 

 

Another: return ab may decide liter Descending

function sort(a,b){
  return a-b  
}

  

Guess you like

Origin www.cnblogs.com/ly-qingqiu/p/10956063.html