TypeScript / JavaScript: Sort Object Array By Property

Let’s see how we can quickly sort TypeScript / JavaScript object array by property.

We will sort the array in following ways:

Consider following products array.

const products: Product[] = [
    { id: 1, name: 'Product 1', price: 100 },
    { id: 2, name: 'Product 2', price: 200 },
    { id: 3, name: 'Product 3', price: 300 },
    { id: 1, name: 'Product 1', price: 100 }
]

Sort the array by property in increasing order

Suppose we want to sort the array by price in increasing order.

We can use array sort method like following.

products.sort((prodA, prodB) => prodA.price > prodB.price ? 1 : -1);

console.table(products);

Output

Sort the array by property in decreasing order

Now let’s sort the products array by price in decreasing order.

products.sort((prodA, prodB) => prodA.price > prodB.price ? -1 : 1);

console.table(products);

Output

Array.prototype.sort()

Sort method sorts the elements of an array and returns the sorted array.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

References:

Array.prototype.sort()

Conclusion

In this post we learned how we can sort the object array by property in ascending and descending order.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s