Sorting arrays in javascript by object key value

前端 未结 6 1949
迷失自我
迷失自我 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"}]

    0 讨论(0)
  • 2020-12-04 17:52

    Here's the same as the current top answer, but in an ES6 one-liner:

    myArray.sort((a, b) => a.distance - b.distance);

    0 讨论(0)
  • 2020-12-04 17:54

    This worked for me

    var files=data.Contents;
              files = files.sort(function(a,b){
            return a.LastModified - b. LastModified;
          });
    

    OR use Lodash to sort the array

    files = _.orderBy(files,'LastModified','asc');
    
    0 讨论(0)
  • 2020-12-04 18:00

    Use Array's sort() method, eg

    myArray.sort(function(a, b) {
        return a.distance - b.distance;
    });
    
    0 讨论(0)
  • 2020-12-04 18:06

    Not spectacular different than the answers already given, but more generic is :

    sortArrayOfObjects = (arr, key) => {
        return arr.sort((a, b) => {
            return a[key] - b[key];
        });
    };
    
    sortArrayOfObjects(yourArray, "distance");
    
    0 讨论(0)
  • 2020-12-04 18:12

    Here is yet another one-liner for you:

    your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);
    
    0 讨论(0)
提交回复
热议问题