Sorting an array of objects by property values - JavaScript

In JavaScript, you can sort an array of objects by property values using the Array.sort() method with a custom comparison function. This is particularly useful when working with data structures like product catalogs, user lists, or any collection of objects.

Sample Data

Let's work with this array of home objects:

const homes = [
    {
        "h_id": "3",
        "city": "Dallas",
        "state": "TX",
        "zip": "75201",
        "price": "162500"
    }, {
        "h_id": "4",
        "city": "Beverly Hills",
        "state": "CA",
        "zip": "90210",
        "price": "319250"
    }, {
        "h_id": "5",
        "city": "New York",
        "state": "NY",
        "zip": "00010",
        "price": "962500"
    }
];

console.log("Original array:", homes);
Original array: [
  {
    h_id: '3',
    city: 'Dallas',
    state: 'TX',
    zip: '75201',
    price: '162500'
  },
  {
    h_id: '4',
    city: 'Beverly Hills',
    state: 'CA',
    zip: '90210',
    price: '319250'
  },
  {
    h_id: '5',
    city: 'New York',
    state: 'NY',
    zip: '00010',
    price: '962500'
  }
]

Sorting by Numeric Property (Ascending)

To sort by price in ascending order, we use parseFloat() to convert string prices to numbers:

const homes = [
    {"h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500"},
    {"h_id": "4", "city": "Beverly Hills", "state": "CA", "zip": "90210", "price": "319250"},
    {"h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500"}
];

const sortByPriceAscending = (arr) => {
    return arr.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
};

const sortedByPrice = sortByPriceAscending([...homes]);
console.log("Sorted by price (ascending):");
console.log(sortedByPrice);
Sorted by price (ascending):
[
  {
    h_id: '3',
    city: 'Dallas',
    state: 'TX',
    zip: '75201',
    price: '162500'
  },
  {
    h_id: '4',
    city: 'Beverly Hills',
    state: 'CA',
    zip: '90210',
    price: '319250'
  },
  {
    h_id: '5',
    city: 'New York',
    state: 'NY',
    zip: '00010',
    price: '962500'
  }
]

Sorting by String Property

To sort by string properties like city names, use localeCompare() for proper alphabetical sorting:

const homes = [
    {"h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500"},
    {"h_id": "4", "city": "Beverly Hills", "state": "CA", "zip": "90210", "price": "319250"},
    {"h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500"}
];

const sortByCity = (arr) => {
    return arr.sort((a, b) => a.city.localeCompare(b.city));
};

const sortedByCity = sortByCity([...homes]);
console.log("Sorted by city:");
console.log(sortedByCity.map(home => `${home.city} - $${home.price}`));
Sorted by city:
[ 'Beverly Hills - $319250', 'Dallas - $162500', 'New York - $962500' ]

Sorting in Descending Order

For descending order, simply reverse the comparison logic:

const homes = [
    {"h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500"},
    {"h_id": "4", "city": "Beverly Hills", "state": "CA", "zip": "90210", "price": "319250"},
    {"h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500"}
];

const sortByPriceDescending = (arr) => {
    return arr.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
};

const sortedDescending = sortByPriceDescending([...homes]);
console.log("Most expensive first:");
console.log(sortedDescending.map(home => `${home.city}: $${home.price}`));
Most expensive first:
[ 'New York: $962500', 'Beverly Hills: $319250', 'Dallas: $162500' ]

Generic Sorting Function

Create a reusable function that can sort by any property:

const sortByProperty = (arr, property, ascending = true) => {
    return arr.sort((a, b) => {
        let comparison = 0;
        
        if (typeof a[property] === 'string') {
            comparison = a[property].localeCompare(b[property]);
        } else {
            comparison = parseFloat(a[property]) - parseFloat(b[property]);
        }
        
        return ascending ? comparison : -comparison;
    });
};

const homes = [
    {"h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500"},
    {"h_id": "4", "city": "Beverly Hills", "state": "CA", "zip": "90210", "price": "319250"},
    {"h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500"}
];

console.log("By price (desc):", sortByProperty([...homes], 'price', false).map(h => h.city));
console.log("By state (asc):", sortByProperty([...homes], 'state', true).map(h => h.state));
By price (desc): [ 'New York', 'Beverly Hills', 'Dallas' ]
By state (asc): [ 'CA', 'NY', 'TX' ]

Key Points

  • Use parseFloat() or Number() for numeric string comparisons
  • Use localeCompare() for proper string sorting
  • The sort() method modifies the original array - use spread operator [...arr] to create a copy
  • Return negative, zero, or positive values in the comparison function for proper sorting

Conclusion

Sorting arrays of objects by property values is straightforward with Array.sort() and custom comparison functions. Use parseFloat() for numeric properties and localeCompare() for strings to ensure accurate sorting results.

Updated on: 2026-03-15T23:18:59+05:30

436 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements