Sorting arrays numerically by object property value
JavascriptArraysSortingJavascript ObjectsJavascript Problem Overview
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" }
]
Javascript Solutions
Solution 1 - Javascript
Use Array.prototype.sort(), eg
myArray.sort((a, b) => a.distance - b.distance)
The sort()
method accepts a comparator function. This function accepts two arguments (both presumably of the same type) and it's job is to determine which of the two comes first.
It does this by returning an integer
- Negative (less-than zero): The first argument comes first
- Positive (greater-than zero): The second argument comes first
- Zero: The arguments are considered equal for sorting
When you're dealing with numeric values, the simplest solution is to subtract the second value from the first which will produce an ascending order result.
Solution 2 - Javascript
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"}]
Solution 3 - Javascript
Here's the same as the current top answer, but in an ES6 one-liner:
myArray.sort((a, b) => a.distance - b.distance);
Solution 4 - Javascript
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');
Solution 5 - Javascript
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");
Solution 6 - Javascript
Push all objects in an array myArray then apply sorting using this.
myArray.sort(function(a, b) {
return a.distance - b.distance;
});
Solution 7 - Javascript
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))
Solution 8 - Javascript
Here is yet another one-liner for you:
your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);
Solution 9 - Javascript
ES6 arrow function:
const orderArrayBy = (arr, key) => arr.sort((a, b) => a[key] - b[key]);