0

How to sort an array of JavaScript objects by property?

JavaScript sort() method sorts the elements of an array in place and returns the sorted array. Keep in mind that this function will modify existing array.

var users = [
  {
    "id": "5cfbee1435e17c31ec7208bc",
    "age": 38,
    "eyeColor": "blue",
    "name": {
      "first": "West",
      "last": "Spence"
    }
  },
  {
    "id": "5cfbee14dae995c1a2bd5c34",
    "age": 22,
    "eyeColor": "brown",
    "name": {
      "first": "Stanton",
      "last": "Fry"
    }
  },
  {
    "id": "5cfbee14221f9f0c1d44941e",
    "age": 21,
    "eyeColor": "blue",
    "name": {
      "first": "Whitney",
      "last": "George"
    }
  },
  {
    "id": "5cfbee14eae09fce9f88a413",
    "age": 39,
    "eyeColor": "brown",
    "name": {
      "first": "Maribel",
      "last": "Gonzales"
    }
  },
  {
    "id": "5cfbee140ad0a54b62cc927a",
    "age": 34,
    "eyeColor": "brown",
    "name": {
      "first": "Galloway",
      "last": "Wilson"
    }
  },
  {
    "id": "5cfbee14cae11341d672f0d2",
    "age": 36,
    "eyeColor": "blue",
    "name": {
      "first": "Bridgett",
      "last": "Weaver"
    }
  },
  {
    "id": "5cfbee1482d4260fd0e10763",
    "age": 20,
    "eyeColor": "green",
    "name": {
      "first": "Vonda",
      "last": "Leonard"
    }
  }
];


// sort by age
users.sort(function(a, b) {
    return a.age - b.age;
});

console.log(users); // sorted by age
RUN

Since ES6 sort will look like this:

var users = [
  {
    "id": "5cfbee1435e17c31ec7208bc",
    "age": 38,
    "eyeColor": "blue",
    "name": {
      "first": "West",
      "last": "Spence"
    }
  },
  {
    "id": "5cfbee14dae995c1a2bd5c34",
    "age": 22,
    "eyeColor": "brown",
    "name": {
      "first": "Stanton",
      "last": "Fry"
    }
  },
  {
    "id": "5cfbee14221f9f0c1d44941e",
    "age": 21,
    "eyeColor": "blue",
    "name": {
      "first": "Whitney",
      "last": "George"
    }
  },
  {
    "id": "5cfbee14eae09fce9f88a413",
    "age": 39,
    "eyeColor": "brown",
    "name": {
      "first": "Maribel",
      "last": "Gonzales"
    }
  },
  {
    "id": "5cfbee140ad0a54b62cc927a",
    "age": 34,
    "eyeColor": "brown",
    "name": {
      "first": "Galloway",
      "last": "Wilson"
    }
  },
  {
    "id": "5cfbee14cae11341d672f0d2",
    "age": 36,
    "eyeColor": "blue",
    "name": {
      "first": "Bridgett",
      "last": "Weaver"
    }
  },
  {
    "id": "5cfbee1482d4260fd0e10763",
    "age": 20,
    "eyeColor": "green",
    "name": {
      "first": "Vonda",
      "last": "Leonard"
    }
  }
];

console.log(users.sort((a, b) => a.name.first.localeCompare(b.name.first))); // sorted by first name
RUN
add comment
Suggest a different solution or add another example