Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting json object based on attribute

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>
like image 551
MayurKode Avatar asked Jan 15 '14 07:01

MayurKode


1 Answers

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);
like image 117
Liju Avatar answered Oct 12 '22 09:10

Liju