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.

JavaScript
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

Similar Reads

Using sort() Function

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....

Using Array.prototype.reduce()

In this approach, we are using Array.prototype.reduce() in JavaScript to sort a JSON object array (jData) based on the ‘est‘ key. The reduce() method iteratively inserts each object into the correct position in a new array (res) by comparing the ‘est‘ values and sorting the array based on the ‘est‘ key....

Using Bubble Sort

In this approach, we are using Bubble Sort in JavaScript to sort a JSON object array (jData) based on the ‘name’ key. The nested loops in JS compare adjacent objects by their ‘name‘ values and swap them if necessary, iterating through the array until it’s sorted in ascending order based on ‘name‘....

Contact Us