Sunday, October 6, 2024
Google search engine
HomeLanguagesJavascriptSort array of objects by string property value in JavaScript

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

Approach 1: Using sort() with a custom compare function

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.

Javascript




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 }
]

Approach 2: 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.

Javascript




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' }
]

Approach 3: Using sort() with a comparison function and the toLowerCase() method

In this approach, sort() with a comparison function and toLowerCase() to sort an array of objects case-insensitively based on a string property.

Example: In this example, we are using the above-explained approach.

Javascript




let GFG_Object = [
    { f_name: 'Geeks', l_name: '_2' },
    { f_name: 'for', l_name: '_1' },
    { f_name: 'GFG', l_name: '_3' }
];
 
GFG_Object.sort((a, b) =>
    a.f_name.toLowerCase().localeCompare(b.f_name.toLowerCase()));
 
console.log(GFG_Object);


Output

[
  { f_name: 'for', l_name: '_1' },
  { f_name: 'Geeks', l_name: '_2' },
  { f_name: 'GFG', l_name: '_3' }
]

RELATED ARTICLES

Most Popular

Recent Comments