12

I have json object array containing firstname, lastname and age. I want to sort array based on age.

<!DOCTYPE html>
<html>
<body>
  <h2>Create Object from JSON String</h2>
  <p>Original name: <span id="origname"></span></p>
  <p>New name: <span id="newname"></span></p>
  <p>Age: <span id="age"></span></p>

  <script>
    var employees = [
      { "firstName" : "John" , "lastName" : "Doe" , "age":"24" }, 
      { "firstName" : "Anna" , "lastName" : "Smith" , "age":"30" }, 
      { "firstName" : "Peter" , "lastName" : "Jones" , "age":"45" }, 
    ];

    document.getElementById("origname").innerHTML=employees[0].firstName + " " + employees[0].lastName;

    // Set new name
    employees[0].firstName="Gilbert";
    document.getElementById("newname").innerHTML=employees[0].firstName + " " + employees[0].lastName;

    document.getElementById("age").innerHTML=employees[0].age;
  </script>
</body>
</html>
DutGRIFF
  • 5,103
  • 1
  • 33
  • 42
MayurKode
  • 135
  • 1
  • 1
  • 8
  • Maybe this answer can will help you http://stackoverflow.com/questions/881510/jquery-sorting-json-by-properties – Liauchuk Ivan Jan 15 '14 at 07:17
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Prinzhorn Jan 15 '14 at 07:20
  • check this link http://stackoverflow.com/questions/8175093/simple-function-to-sort-a-json-object-using-javascript – Shyam Dixit Jan 15 '14 at 07:26
  • 1
    You don't have a JSON object array. It is just an object array. JSON is a string representation of the object. They look a lot alike but they are not the same. You can make this into JSON with `JSON.stringify(employees);`. – DutGRIFF Jan 15 '14 at 07:27
  • http://stackoverflow.com/questions/881510/jquery-sorting-json-by-properties – Hüseyin BABAL Jan 15 '14 at 07:29

1 Answers1

22

var employees = [{
    "firstName": "Anna",
    "lastName": "Smith",
    "age": "30"
  },
  {
    "firstName": "John",
    "lastName": "Doe",
    "age": "24"
  },
  {
    "firstName": "Peter",
    "lastName": "Jones",
    "age": "45"
  }
];

function sortByKey(array, key) {
  return array.sort(function(a, b) {
    var x = a[key];
    var y = b[key];
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  });
}

people = sortByKey(employees, 'age');

console.log(people);
tr05t
  • 47
  • 1
  • 10
Liju
  • 687
  • 1
  • 7
  • 16