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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With