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

1 Answer 1

23

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I love this solution. However, is there a way to make it access a 'grandchild' attribute of the object? For example sortByKey(myArr, 'myList.myElement')
Could someone explain the logic?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.