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
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"}]
Here's the same as the current top answer, but in an ES6 one-liner:
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');
Use Array's sort() method, eg
myArray.sort(function(a, b) {
return a.distance - b.distance;
});
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");
Here is yet another one-liner for you:
your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);