Sorting an array of objects by property values

Cover Image for Sorting an array of objects by property values
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Sorting an Array of Objects by Property Values: A Complete Guide

So you've got an array of objects and you want to sort them by a specific property value? No worries, I've got you covered! In this guide, I'll walk you through the steps to create a function that can sort your objects in ascending or descending order using JavaScript only. Let's dive in!

The Problem

Let's take a look at the array of objects we're dealing with:

var 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"
    }
];

We want to sort these objects by the price property in either ascending or descending order.

The Solution

To achieve this, we can use the sort() method in JavaScript. The sort() method sorts the elements of an array in place and returns the sorted array.

Here's how we can create a function to sort the objects by the price property:

function sortByPrice(array, order) {
    return array.sort((a, b) => {
        const priceA = parseInt(a.price);
        const priceB = parseInt(b.price);

        if (order === 'asc') {
            return priceA - priceB;
        } else if (order === 'desc') {
            return priceB - priceA;
        }
    });
}

Let's break it down:

  1. We define a function called sortByPrice that takes two parameters: the array to be sorted (array) and the sorting order (order), which can be either 'asc' for ascending order or 'desc' for descending order.

  2. We use the sort() method on the array parameter and pass in a comparison function as an argument.

  3. Inside the comparison function, we convert the price property of each object to an integer using the parseInt() function. This ensures that the sorting is performed based on numerical values rather than strings.

  4. We check the order parameter and return the appropriate value to determine the sort order. If order is 'asc', we subtract priceA from priceB to sort in ascending order. If order is 'desc', we subtract priceB from priceA to sort in descending order.

  5. Finally, we return the sorted array.

Example Usage

Let's see our function in action! Here are a couple of examples to demonstrate how you can use it:

// Sort in ascending order
const sortedHomesAsc = sortByPrice(homes, 'asc');
console.log(sortedHomesAsc);

// Sort in descending order
const sortedHomesDesc = sortByPrice(homes, 'desc');
console.log(sortedHomesDesc);

Output:

// Ascending Order
[
    {
        "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"
    }
]

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

As you can see, the objects in the homes array have been sorted based on the price property in the desired order.

Conclusion

Sorting an array of objects by property values in JavaScript is made simple with the sort() method. By following the steps outlined in this guide and using the provided sortByPrice function, you can easily sort your objects in ascending or descending order.

So why wait? Give it a try and sort your arrays with ease! Feel free to share your thoughts and experiences in the comments below. Happy coding! 🚀


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello