Sorting arrays in javascript by object key value

前端 未结 6 1970
迷失自我
迷失自我 2020-12-04 17:44

How would you sort this array with these objects by distance. So that you have the objects sorted from smallest distance to biggest distance ?

Object { dista         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 17:48

    here's an example with the accepted answer:

     a = [{name:"alex"},{name:"clex"},{name:"blex"}];
    

    For Ascending :

    a.sort((a,b)=> (a.name > b.name ? 1 : -1))
    

    output : [{name: "alex"}, {name: "blex"},{name: "clex"} ]

    For Decending :

    a.sort((a,b)=> (a.name < b.name ? 1 : -1))
    

    output : [{name: "clex"}, {name: "blex"}, {name: "alex"}]

提交回复
热议问题