How to use Bubble Sort In JSON
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‘.
Example: The below example uses the Bubble Sort to sort JSON Object Arrays based on a Key.
let jData = [
{ name: "w3wiki", est: 2009 },
{ name: "Google", est: 1998 },
{ name: "Microsoft", est: 1975 }
];
for (let i = 0; i < jData.length - 1; i++) {
for (let j = 0; j < jData.length - i - 1; j++) {
if (jData[j].name > jData[j + 1].name) {
let temp = jData[j];
jData[j] = jData[j + 1];
jData[j + 1] = temp;
}
}
}
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