101

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
  • 16,564
  • 7
  • 51
  • 69
Harry
  • 12,005
  • 27
  • 100
  • 164
  • 1
    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

9 Answers9

207

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
  • 141,914
  • 21
  • 225
  • 223
  • 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
57

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
  • 671
  • 5
  • 4
25

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
  • 513
  • 5
  • 7
7

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
  • 359
  • 1
  • 5
  • 12
5

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");
  • 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
3

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

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});
Deepak Kumar
  • 213
  • 3
  • 15
3

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
  • 304
  • 3
  • 11
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
  • 6,414
  • 4
  • 20
  • 33
0

ES6 arrow function:

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