JSON Sort Objects in Descending Order

JSON Sort Objects in Descending Order

In the following example, we will sort objects in an array in descending order with respect to the user-specified property (either name or age).

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <body> <h1>JSON sort descending</h1> <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> </body> </html>

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author