131

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" }
]
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Harry
  • 13,091
  • 29
  • 107
  • 167
  • 3
    The pattern for [sorting by properties](/q/2466356/4642212) numerically is `myarray.sort((a, b) => a.distance - b.distance)`. To sort [lexicographically](/q/1129216/4642212), use `a.from.localeCompare(b.from)`. To sort descending instead of ascending, negate the return value (e.g. `b.distance - a.distance` instead of `a.distance - b.distance`). To sort [numeric _strings_](/q/979256/4642212), optionally use `Number`. To sort by [multiple properties](/q/6913512/4642212), chain other sorts with `||`, e.g. `b.someNumber - a.someNumber || a.someString.localeCompare(b.someString)`. – Sebastian Simon Apr 10 '22 at 11:49

10 Answers10

249

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.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    Alternative, using [destructuring assignment](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment): `myArray.sort(({ distance: a }, { distance: b }) => a - b);`. – Sebastian Simon Apr 10 '22 at 11:46
  • 3
    @SebastianSimon that's not an _alternative_ so much as it is the same thing but 10 characters longer syntactically. Potato / tomato – Phil Aug 01 '22 at 05:49
76

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"}]

Surya Murugan
  • 861
  • 6
  • 4
  • Just in addition to this, don't forget to change data in comparing function to either upper or lower case, so that you get results as in alphabetical order irrespective of ASCII code. – Akash Jul 13 '22 at 13:36
26

Here's the same as the current top answer, but in an ES6 one-liner:

myArray.sort((a, b) => a.distance - b.distance);

Jon Tonti
  • 533
  • 5
  • 7
8

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');
Vinod Poorma
  • 419
  • 1
  • 6
  • 15
6

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");
Arthur van Acker
  • 472
  • 7
  • 10
  • 1
    Can be written with a one liner return statement: `sortArrayOfObjects = (arr, key) => { return arr.sort((a, b) => a[key] - b[key]); };` – user10971804 Feb 28 '20 at 05:25
4

Push all objects in an array myArray then apply sorting using this.

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});
Deepak Kumar
  • 221
  • 3
  • 17
4

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))
laurisstepanovs
  • 432
  • 5
  • 14
0

Here is yet another one-liner for you:

your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);
codemonkey
  • 7,325
  • 5
  • 22
  • 36
0

ES6 arrow function:

const orderArrayBy = (arr, key) => arr.sort((a, b) => a[key] - b[key]);
niikoo
  • 11
  • 4
0

You can use Currying for this:

const arr = [
  { distance: 3388, duration: 6},
  { distance: 13564, duration: 12},
  { distance: 4046, duration: 6 },
  { distance: 11970, duration: 17 }
]

const sortByKey = (key) => (a, b) => b[key] - a[key];

const sortByDistance = sortByKey("distance");
const sortByDuration = sortByKey("duration");

console.log(arr.sort(sortByDistance))
console.log(arr.sort(sortByDuration))
Andrey Horsev
  • 81
  • 2
  • 4