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...}
This question is related to
javascript
arrays
sorting
object
Here's the same as the current top answer, but in an ES6 one-liner:
myArray.sort((a, b) => 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"}]
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");
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');
Here is yet another one-liner for you:
your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);
Source: Stackoverflow.com