Javascript 按对象键值对javascript中的数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7889006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:57:41  来源:igfitidea点击:

Sorting arrays in javascript by object key value

javascriptarrayssortingobject

提问by Harry

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 { distance=3388, duration="6 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

Object { distance=13564, duration="12 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

Object { distance=4046, duration="6 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

Object { distance=11970, duration="17 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

回答by Phil

Use Array's sort()method, eg

使用Arraysort()方法,例如

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});

回答by HMagdy

If the key value is type of stringyou could use localeComparemethod like:

如果键值是类型,string您可以使用如下localeCompare方法:

users.sort((a, b) => a.name.localeCompare(b.name));

回答by Jon Tonti

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

这与当前的最佳答案相同,但在 ES6 单行中:

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

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

回答by Vinod Poorma

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

或使用 Lodash 对数组进行排序

files = _.orderBy(files,'LastModified','asc');

回答by Arthur van Acker

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");