Sorting arrays in javascript by object key value
Use Array
's sort()
method, eg
myArray.sort(function(a, b) {
return a.distance - b.distance;
});
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"}]