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" }
]
const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.
To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.
To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
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
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With