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 comment