How to use sort() Function In JSON
In this approach, we are using the sort() function in JavaScript to sort a JSON object array (jData) based on the ‘name‘ key. The sorting is done by comparing the ‘name‘ values of each object using a comparator function within the sort() method.
Syntax:
obj.sort((a, b) => a - b);
Example: The below example uses the sort() function to sort JSON Object Arrays based on a Key.
let jData = [
{ name: "w3wiki", est: 2009 },
{ name: "Google", est: 1998 },
{ name: "Microsoft", est: 1975 }
];
jData.sort((a, b) => (a.name > b.name ? 1 : -1));
console.log(jData);
Output
[ { name: 'w3wiki', est: 2009 }, { name: 'Google', est: 1998 }, { name: 'Microsoft', est: 1975 } ]
How to Sort JSON Object Arrays Based on a Key?
Sorting is the process of arranging elements in a specific order. In JavaScript, we can sort a JSON array by key using various methods, such as the sort() function. Along with this, we can use various other approaches and methods that are implemented in this article.
Below are the approaches to sort JSON Object Arrays based on a Key:
Table of Content
- Using sort() Function
- Using Array.prototype.reduce()
- Using Bubble Sort
Contact Us