Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

Sort Array of Objects by String Property Value in JavaScript

Posted on December 14, 2024 By Admin No Comments on Sort Array of Objects by String Property Value in JavaScript

Sorting arrays of objects is a common task when working with JavaScript, especially when you need to organize data based on specific properties. In this article, we will explore how to sort an array of objects based on a string property value, covering various approaches to achieve this.

1. Sorting with the sort() Method

JavaScript provides the Array.prototype.sort() method, which can be used to sort arrays in place. By default, the sort() method sorts elements as strings in lexicographical order. However, when sorting objects, we need to provide a custom comparison function to specify how the sorting should be done based on the string property.

Sort in Ascending Order

To sort the array in ascending order (alphabetically), you can use the following approach:

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 }
];

const sortedPeople = people.sort((a, b) => {
    if (a.name < b.name) {
        return -1; // a comes before b
    }
    if (a.name > b.name) {
        return 1; // b comes before a
    }
    return 0; // names are equal
});

console.log(sortedPeople);

Explanation

  • The comparison function checks the name properties of two objects at a time (a and b).
  • If a.name is lexicographically less than b.name, it returns -1 to indicate that a should come before b.
  • If a.name is greater than b.name, it returns 1 to indicate that b should come before a.
  • If the names are equal, it returns 0 to leave them in their original order.

Sort Array in Descending Order

To sort the array in descending order (reverse alphabetical order), simply reverse the logic:

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 }
];

const sortedPeopleDescending = people.sort((a, b) => {
    if (a.name < b.name) {
        return 1; // b comes before a
    }
    if (a.name > b.name) {
        return -1; // a comes before b
    }
    return 0; // names are equal
});

console.log(sortedPeopleDescending);

Explanation

  • The comparison function now returns 1 when a.name is less than b.name, and -1 when a.name is greater than b.name, thus reversing the order.

2. Using localeCompare() for Sorting Strings

JavaScript String localeCompare() method provides a more robust way to compare strings, especially when dealing with different character sets, such as non-English alphabets. It returns a number indicating whether the reference string (a.name) is less than, equal to, or greater than the compared string (b.name).

Ascending Order with localeCompare() Method

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 }
];

const sortedPeople = people.sort((a, b) => a.name.localeCompare(b.name));

console.log(sortedPeople);

Explanation

  • The localeCompare() method is used to compare the name properties of the objects.
  • It returns -1 if a.name is lexicographically smaller, 1 if it is larger, and 0 if the strings are equal.
  • This approach is more efficient and handles international characters better than manually comparing strings with < and >.

Descending Order with localeCompare() Method

For descending order, just swap the order of a and b in the localeCompare() method:

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 }
];

const sortedPeopleDescending = people.sort((a, b) => b.name.localeCompare(a.name));

console.log(sortedPeopleDescending);

3. Case-Insensitive Sorting

In many scenarios, you might want to ignore case when sorting strings. This can be achieved by converting the strings to a common case (lowercase or uppercase) before comparison.

Ascending Order (Case-Insensitive)

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 }
];

const sortedPeople = people.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));

console.log(sortedPeople);

Descending Order (Case-Insensitive)

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 }
];

const sortedPeopleDescending = people.sort((a, b) => b.name.toLowerCase().localeCompare(a.name.toLowerCase()));

console.log(sortedPeopleDescending);

4. Sorting with Multiple Criteria

In some cases, you may want to sort by multiple properties. For example, you might want to sort first by the name property and then by age if the names are equal.

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 },
    { name: "John", age: 22 }
];

const sortedPeople = people.sort((a, b) => {
    const nameComparison = a.name.localeCompare(b.name);

    if (nameComparison !== 0) {

        // If names are different, return 
        // the result of name comparison
        return nameComparison; 
    }

    // If names are the same, sort by age
    return a.age - b.age;
});

console.log(sortedPeople);  

Explanation

  • The primary sorting is done by name, using localeCompare().
  • If the names are the same (i.e., nameComparison === 0), the secondary sorting is done by age in ascending order.

5. Sorting by String Length

If you want to sort by the length of a string property (e.g., the name property), you can do so by comparing the length of the strings:

Ascending Order by Length

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 },
    { name: "John", age: 22 }
];

const sortedPeopleByLength = people.sort((a, b) => a.name.length - b.name.length);

console.log(sortedPeopleByLength);

Descending Order by Length

const people = [
    { name: "John", age: 25 },
    { name: "Alice", age: 30 },
    { name: "Bob", age: 20 },
    { name: "John", age: 22 }
];

const sortedPeopleByLengthDescending = people.sort((a, b) => b.name.length - a.name.length);

console.log(sortedPeopleByLengthDescending);

Explanation

  • a.name.length - b.name.length sorts by the length of the name property in ascending order.
  • b.name.length - a.name.length sorts by length in descending order.

JavaScript, Web Technologies Tags:JavaScript-Array, JavaScript-Method

Post navigation

Previous Post: Loop (forEach) over an array in JavaScript
Next Post: JavaScript Array.length Property

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme