sorting by a user-defined function.
This function compares the array of objects by its property. this example compares the l_name of objects and if l_name is small then it places into the left otherwise place it into the right position.
Example: In this example, we are using the above-explained approach.
let GFG_Object = [
{ f_name: 'Geeks', l_name: '_2' },
{ f_name: 'for', l_name: '_1' },
{ f_name: 'GFG', l_name: '_3' }
];
GFG_Object.sort(compare);
function compare(a, b) {
if (a.l_name < b.l_name)
return -1;
if (a.l_name > b.l_name)
return 1;
return 0;
}
console.log(GFG_Object);
Output
[ { f_name: 'for', l_name: '_1' }, { f_name: 'Geeks', l_name: '_2' }, { f_name: 'GFG', l_name: '_3' } ]
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