<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>JSON sort descending</h1>
<p>Sort the objects in the array in descending 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 (b[key] > a[key]) ? 1 : ((b[key] < a[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>