How to usesort() with a custom compare function in Javascript
In this approach, sort() is used with a custom compare function that utilizes localeCompare() to sort the array of objects by a string property value.
Example: In this example, we are using the above-explained approach.
const GFG_object = [
{ name: "Rahul", age: 30 },
{ name: "Aman", age: 25 },
{ name: "Deepak", age: 35 }
];
let result = GFG_object.sort((a, b) =>
a.name.localeCompare(b.name));
console.log(result);
Output
[ { name: 'Aman', age: 25 }, { name: 'Deepak', age: 35 }, { name: 'Rahul', age: 30 } ]
Sort array of objects by string property value in JavaScript
In this article, we will see how to sort an array of objects by string property value in JavaScript. The array of objects can be sorted by using a user-defined function.
Here we have some common approaches to sorting an array of objects by string property value
- Using sort() with a custom compare function
- sorting by a user-defined function
- Using sort() with a comparison function and the toLowerCase() method
Contact Us