简体   繁体   中英

Sorting arrays numerically by object property value

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

[
  { distance: 3388, duration: "6 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
  { distance: 13564, duration: "12 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
  { distance: 4046, duration: "6 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
  { distance: 11970, duration: "17 mins", from: "Lenchen Ave, Centurion 0046, South Africa" }
]

Use Array 's sort() method , eg

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

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"}]

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

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

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

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

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

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

这是给你的另一个单线:

your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);

ES6 箭头函数:

const orderArrayBy = (arr, key) => arr.sort((a, b) => a[key] - b[key]);

Push all objects in an array myArray then apply sorting using this.

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

If you have lowercase and uppercase names, use toLowerCase() function.
Here is an example:

data = [{name:"foo"},{name:"Bar"},{name:"Foo"}];


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

You can use Currying for this:

const arr = [
  { distance: 3388, duration: 6},
  { distance: 13564, duration: 12},
  { distance: 4046, duration: 6 },
  { distance: 11970, duration: 17 }
]

const sortByKey = (key) => (a, b) => b[key] - a[key];

const sortByDistance = sortByKey("distance");
const sortByDuration = sortByKey("duration");

console.log(arr.sort(sortByDistance))
console.log(arr.sort(sortByDuration))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM