<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>JSON sort ascending</h1>
<p>Sort the objects in the array in ascending order with respect to 'name' key/value pair.</p>
<button onclick="myFunction()">Click Me</button>
<script>
var data = [
{
"name": "Danny",
"age": 25
},
{
"name": "Mike",
"age": 35
},
{
"name": "Jade",
"age": 18
}
]
function mySort(obj, key) {
obj.sort(function(a, b) {
return (a[key] > b[key]) ? 1 : ((a[key] < b[key]) ? -1 : 0);
});
console.log(data);
}
function myFunction(){
mySort(data, 'name');
}
</script>
<p><strong>Note</strong>: Click on the button and check your console</p> </body>
</html>