Sort JavaScript Array by Key in Ascending & Descending Order

Last modified on January 6, 2020 29 sec read

In this article, we are going to learn how to sort JavaScript array by key. Let’s take an array:

let products = [
    {name: "Product 1", price: 32.34},
    {name: "Product 2", price: 10.23},
    {name: "Product 3", price: 22.75},
    {name: "Product 4", price: 16.95},
]

We’ll sort the array by price in ascending & descending order. We will use array.sort() method. Let’s see the syntax:

// ascending order
array.sort((a, b) => a.key - b.key)
// descending order
array.sort((a, b) => b.key - a.key)

Ascending Order

We’ve seen the syntax. Now let’s apply the ascending formula on our products array.

products.sort((a, b) => a.price - b.price)

If you print the result in the console, the result will look like:

Descending Order

Like ascending, let’s apply descending order:

products.sort((a, b) => b.price- a.price)

and the result will look like:

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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